Vba hyperlink excel cell

Создание гиперссылки в VBA Excel методом Hyperlinks.Add для перехода на другой лист, на интернет-сайт, для открытия любого файла в программе по умолчанию.

Hyperlinks.Add — это метод, который добавляет новую гиперссылку к указанному объекту Range (диапазону, ячейке) или объекту Shape (фигуре).

Синтаксис

Expression.Add (Anchor, Address, SubAddress, ScreenTip, TextToDisplay)

Expression — выражение (переменная), возвращающее объект Hyperlinks.

Параметры

Параметр Описание
Anchor Объект Range или объект Shape, к которому привязывается (добавляется) новая гиперссылка. Обязательный параметр. Тип данных — Object.
Address Адрес гиперссылки. Обязательный параметр. Тип данных — String.
SubAddress Субадрес гиперссылки. Необязательный параметр. Тип данных — Variant.
ScreenTip Всплывающая подсказка, отображаемая при наведении указателя мыши на текст гиперссылки. Необязательный параметр. Тип данных — Variant.
TextToDisplay Текст гиперссылки. Необязательный параметр. Тип данных — Variant.

Если текст гиперссылки (TextToDisplay) не указан, будет отображен текст параметров Address и SubAddress.

Создание гиперссылки на рабочий лист другой книги:

ActiveSheet.Hyperlinks.Add Anchor:=Range(«A4»), Address:=«C:UsersEvgeniyDesktopКнига2.xlsx», _

    SubAddress:=«Лист3!D5», ScreenTip:=«Гиперссылка на Лист3!D5 в Книга2», TextToDisplay:=«Книга2 — Лист3!D5»

Создание гиперссылки на другой лист текущей книги:

ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=«», _

    SubAddress:=«Лист4!D6», TextToDisplay:=«Эта книга — Лист4!D6»

Создание гиперссылки на другую ячейку того же листа:

Worksheets(«Лист1»).Hyperlinks.Add Anchor:=Range(«A1»), Address:=«», _

    SubAddress:=«Лист1!D6», TextToDisplay:=«Перейти к D6»

Создание гиперссылки на документ Word:

ActiveSheet.Hyperlinks.Add Anchor:=Range(«A1»), Address:=«C:UsersEvgeniyDocumentsДокумент 1.docx», _

    TextToDisplay:=«Ссылка на Документ 1»

Создание гиперссылки на точечный рисунок:

ActiveSheet.Hyperlinks.Add Anchor:=Range(«A1»), Address:=«C:UsersEvgeniyDocumentsРисунок 1.bmp», _

    TextToDisplay:=«Ссылка на Рисунок 1»

Пример добавления гиперссылки на рубрику «VBA Excel» сайта «Время не ждёт»:

ActiveSheet.Hyperlinks.Add Anchor:=Range(«A1»), Address:=«https://vremya-ne-zhdet.ru/category/vba-excel/», _

    TextToDisplay:=«Рубрика VBA Excel»

Поиск первой ячейки с гиперссылкой в заданном диапазоне:

Sub Primer()

Dim myRange As Range, n As Integer, i As Integer, s As String

‘Задаем диапазон поиска

Set myRange = Range(«A1:G10»)

‘Вычисляем количество ячеек в заданном диапазоне

n = myRange.Cells.Count

‘Ищем первую ячейку с гиперссылкой

    For i = 1 To n

        If myRange.Cells(i).Hyperlinks.Count > 0 Then

            s = myRange.Cells(i).Address

            Exit For

        End If

    Next

MsgBox s

End Sub

Для поиска последней ячейки с гиперссылкой в заданном диапазоне следует заменить строку
For i = 1 To n
на
For i = n To 1 Step -1.


In this Article

  • VBA Hyperlinks
    • Add a Hyperlink with VBA
    • Adding Text to Display with VBA
    • Adding a ScreenTip with VBA
    • Delete a Hyperlink with VBA
    • Delete all the Hyperlinks in a Worksheet
    • Follow a Website Hyperlink Using VBA
    • Follow a Hyperlink to a Folder on Your Drive
    • Follow a Hyperlink to a File on Your Drive
    • Go to a Cell in another sheet in the same Workbook
    • Display all the Hyperlinks in a Worksheet
    • Display all the Hyperlinks in a Workbook
    • Using the FollowHyperlink Method to Create Emails
    • Adding a Hyperlink to an AutoShape in Excel
    • Inserting the Hyperlink Formula into a Cell Using VBA
    • Adding a Hyperlink to a Button in Access
    • Creating a Hyperlink from a Selection in Word

This VBA Tutorial covers the different ways to work with hyperlinks in VBA.

VBA Hyperlinks

With VBA, you can add hyperlinks, remove hyperlinks, create emails using hyperlinks, and open files using hyperlinks in VBA.

Add a Hyperlink with VBA

The Hyperlinks.Add Method adds a hyperlink to a cell using VBA.

The following code will add a hyperlink to cell A1:

Sub AddHyperlinkToCell()
  ActiveSheet.Hyperlinks.Add Range("A1"), Address:="https://www.automateexcel.com/excel/"
End Sub

The result is:

Add a Hyperlink to a Cell with VBA

Adding Text to Display with VBA

You can add neat user-friendly text to display to your hyperlink with VBA. If you used the worksheet functionality you would insert a hyperlink and then add a text to display in the dialog box provided.

The code below demonstrates how to add text to display to your hyperlink using VBA:

Sub TextToDisplayForHyperlink()
  ActiveSheet.Hyperlinks.Add Range("A1"), Address:="https://www.automateexcel.com/excel/", TextToDisplay:="Automate Excel"
End Sub

The result is:

Add Text To Display Using VBA

Adding a ScreenTip with VBA

You can add a ScreenTip to your hyperlink that the viewer will see when they hover over the link.

The code below shows how to add a ScreenTip to your hyperlink using VBA:

Sub ScreenTipForHyperlink()
  ActiveSheet.Hyperlinks.Add Range("A1"), Address:="https://www.automateexcel.com/excel/", TextToDisplay:="Automate Excel", ScreenTip:="This is the link for Automate Excel"
End Sub

The result is:

Add a ScreenTip to the Hyperlink Using VBA

Delete a Hyperlink with VBA

The Hyperlinks.Delete Method can be used to delete a hyperlink from a cell.

The following code will delete the hyperlink from cell A1 and the text in the cell.

Note that just deleting the hyperlink, does not delete the text itself that’s why if you want the text deleted you also have to use the Clear method.

Sub DeleteHyperlinkinCell()
  Range("A1").Hyperlinks.Delete
  Range("A1").Clear
End Sub

Delete all the Hyperlinks in a Worksheet

You can also delete all the hyperlinks in your worksheet using the Hyperlinks.Delete method.

The following code will delete all the hyperlinks in the first worksheet in your workbook:

Sub RemoveAllHyperlinksInASheet()
  ThisWorkbook.Sheets(1).Hyperlinks.Delete
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Follow a Website Hyperlink Using VBA

The following code allows you to open a website address, in a new window in your browser using the FollowHyperlink method in your workbook:

Sub FollowHyperlinkForWebsite()
  ActiveWorkbook.FollowHyperlink Address:="https://www.automateexcel.com/excel", NewWindow:=True
End Sub

Follow a Hyperlink to a Folder on Your Drive

The following code will open a folder called ExcelFiles on the Desktop using the FollowHyperlink Method:

Sub FollowHyperlinkForFolderOnDrive()
  ActiveWorkbook.FollowHyperlink Address:="C:DesktopExcelFiles"
End Sub

Follow a Hyperlink to a File on Your Drive

The following code will open an Excel file called WorkbookOne in the folder called ExcelFiles on the Desktop using the FollowHyperlink Method:

Sub FollowHyperlinkForFile()
  ActiveWorkbook.FollowHyperlink Address:="C:DesktopExcelFilesWorkbookOne.xlsx", NewWindow:=True
End Sub

VBA Programming | Code Generator does work for you!

Go to a Cell in another sheet in the same Workbook

You can add a hyperlink to a cell in one sheet that takes you to another sheet, in the same workbook with VBA. Let’s say you are on Sheet1, cell A1 of your workbook and you want to insert a hyperlink to Sheet2, cell B2 of the same workbook, you can use the SubAddress property to do this.

The following code demonstrates how to do this:

Sub GoToAnotherCellInAnotherSheetInTheSameWorkbook()
  ActiveSheet.Hyperlinks.Add Range("A1"), Address:="", SubAddress:="'" & Sheet2.Name & "'!B2", TextToDisplay:="Click Here to Go to Sheet2, cell B2 of the same workbook"
End Sub

Display all the Hyperlinks in a Worksheet

You can access the hyperlinks collection and display all the hyperlinks in your worksheet in the Intermediate window in the VBA Editor. You must first press CTRL+G on your keyboard or go to View>Intermediate Window in the VBE Editor, to view the Intermediate Window.

The following code shows how to view the hyperlinks in your worksheet in the Intermediate Window:

Sub ShowAllTheHyperlinksInTheWorksheet()

Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets(1)

For Each lnk In ws.Hyperlinks
Debug.Print lnk.Address
Next lnk

End Sub

The results are shown in the Intermediate Window.

Show all Hyperlinks in the Intermediate Window Using VBA

Display all the Hyperlinks in a Workbook

You can access the hyperlinks collection, to loop through and display all the hyperlinks in your Workbook in a Message Box.

The following code shows how to do this, and uses a nested loop in order to achieve this:

Sub ShowAllTheHyperlinksInTheWorkbook()

Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
For Each lnk In ws.Hyperlinks
MsgBox lnk.Address
Next lnk
Next ws

End Sub

Using the FollowHyperlink Method to Create Emails

You can also create emails using the FollowHyperlink Method.

The code below will show you how to create emails using the FollowHyperlink Method in VBA:

Sub SendEmailUsingHyperlink()

Dim msgLink As String

msgLink = "mailto:" & "person@email.com" & "?" & "subject=" & "Hello" & "&" & "body=" & "How are you?"
ActiveWorkbook.FollowHyperlink (msgLink)

End Sub

The result is:

Using Hyperlinks to Create Emails in VBA

Adding a Hyperlink to an AutoShape in Excel

You can add a hyperlink to an Autoshape in Excel so that when the user clicks on the shape they get taken to a website address.

The following code creates a rounded rectangle, adds the text to the rectangle and adds a hyperlink to the rectangle:

Sub AddingAHyperlinkToAShape()

Dim myShape As Shape
Set myDocument = Worksheets("Sheet1")
Set myShape = myDocument.Shapes.AddShape(msoShapeRoundedRectangle, 100, 100, 90, 30)

With myShape
.TextFrame.Characters.Text = "Automate Excel"
End With

ActiveSheet.Hyperlinks.Add Anchor:=myShape, Address:="https://www.automateexcel.com/excel"

End Sub

The result is:
Adding a Hyperlink to An Autoshape in VBA

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Inserting the Hyperlink Formula into a Cell Using VBA

Let’s say you have a post title in cell A4 and a post link in cell B4 as shown in the image below.

Inserting a Hyperlink Using a Formula with VBA

A quick reminder of the worksheet Hyperlink formula syntax is:

HYPERLINK(link_location, [friendly_name])

link_location – This is the link to the document, file, place in the workbook or online site.

friendly_name – (Optional) – The text or numeric value that is displayed in the cell.

In cell C4, you want to add the hyperlink with a friendly text to display, now usually you would enter the formula =HYPERLINK(B4,A4) in C4 to get the following:

Using the Hyperlink Worksheet Formula in VBA

You could instead use VBA to achieve the same result, and insert this formula in the cell, on Sheet1 with the following code:

Sub InsertHyperlinkFormulaInCell()
  ActiveWorkbook.Worksheets("Sheet1").Range("C4").Formula = "=hyperlink(B4,A4)"
End Sub

Adding a Hyperlink to a Button in Access

VBA allows you to work with hyperlinks in Access too. Let’s say we have a button on a form and when the user clicks on that button we want them to be taken to a website. One way that you can use to do this, is through the Application.FollowHyperlink method.

We have our sample form with a button called buttonOne shown below.

Adding a Hyperlink in Access Using VBA

The code for this button would be:

Private Sub buttonOne_Click()

Application.FollowHyperlink ("https://www.automateexcel.com/excel/")

End Sub

Creating a Hyperlink from a Selection in Word

You can work with hyperlinks in Word VBA as well.
Let’s say we have text in Word that says “Click Here to Be Taken to the Automate Excel Website”, that is selected as shown below.

Adding a Hyperlink using VBA in Word

To turn this text into a hyperlink using VBA, you can use the following code:

Private Sub TurnASelectionIntoAHyperlink()
  ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="https://www.automateexcel.com/excel/", ScreenTip:="Click Here Please", Target:=NewWindow
End Sub

The result is:

Adding a Hyperlink to a Selected Text in Word with VBA

Hyperlinks are URL attached to a value that one may see when we hover the mouse over it. When we click on it, the URL opens. In VBA, we have an inbuilt property to create hyperlinks in VBA. To use this property, we must use the Add method together with the hyperlink statement to insert a hyperlink in a cell.

Hyperlinks in Excel VBA

Even though we have Page Up and Page Down shortcut key in excelAn Excel shortcut is a technique of performing a manual task in a quicker way.read more to move from one sheet to another. But it becomes complex when we have to move between 10 to more worksheets. It is where the beauty of “Hyperlinks in Excel” comes into the picture. The hyperlink is a predetermined URL that takes you to the respective cell or worksheet as assigned.

We all know how to quickly create hyperlinks in the worksheet to move from one sheet to another. But, of course, you can also go to any other sheet. But in today’s article, we will show you how to create hyperlinks using VBA coding.

Table of contents
  • Hyperlinks in Excel VBA
    • The formula of VBA Hyperlinks
    • How to Create Hyperlinks in Excel VBA?
    • Hyperlinks of Multiple Sheets with Loops
    • Recommended Articles

VBA Hyperlinks

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Hyperlinks (wallstreetmojo.com)

The formula of VBA Hyperlinks

Let us look at the formula of the hyperlinks in Excel VBA.

VBA Hyperlink Formula

  • Anchor: In which cell would you like to create a hyperlink?
  • Address: What is the URL to the hyperlink to navigate?
  • [Sub Address]: What is the location of the page?
  • [Screen Tip]: What is the value shown when you place a mouse pointer on the hyperlink name or cell?
  • [Text to Display]: What test will display in the cell? For example, Worksheet Name.

How to Create Hyperlinks in Excel VBA?

You can download this VBA Hyperlinks Template here – VBA Hyperlinks Template

Assume you want to create a VBA hyperlink to the “Main Sheet” sheet from the other sheet, “Example 1.”

VBA Hyperlinks Example 1

In the worksheet “Example 1” and cell A1, we will create the hyperlink using Code in VBAVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Step 1: First, select the cell A1 of the worksheet example 1.

Code:

Sub Hyperlink_Example1()

   Worksheets("Example 1").Select
   Range("A1").Select

End Sub

VBA Hyperlinks Example 1-1

Step 2: Now, open hyperlinks using the Active Cell object. Add method.

Code:

Sub Hyperlink_Example1()

  Worksheets("Example 1").Select
  Range("A1").Select

  ActiveCell.Hyperlinks.Add(

End Sub

VBA Hyperlinks Example 1-2

Step 3: The first argument is “Anchor,” i.e., in which cell we would link to create the VBA hyperlink. In this case, cell A1 and since we have already selected cell A1 to mention it as “Selection.”

Code:

Sub Hyperlink_Example1()

   Worksheets("Example 1").Select
   Range("A1").Select

   ActiveCell.Hyperlinks.Add(Selection,

End Sub

VBA Hyperlinks Example 1-3

Step 4: We are not creating any address here, so ignore the Address as of now.

Code:

Sub Hyperlink_Example1()

   Worksheets("Example 1").Select
   Range("A1").Select

   ActiveCell.Hyperlinks.Add Anchor:= Selection, Address:="",
 
End Sub

VBA Hyperlinks Example 1-4

Step 5: Next is ‘Sub Address.’ Here, we need to mention which sheet we are referring to and the first cell of that sheet.

Code:

Sub Hyperlink_Example1()

Worksheets("Example 1").Select
Range("A1").Select

ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'Main Sheet'!A1",

End Sub

VBA Hyperlinks Example 1-5

We have mentioned the sheet name as “Main Sheet.” In that sheet cell address is “A1.”

Step 6: Ignore the screen tip as well. For text to display, mention the sheet name.

Code:

Sub Hyperlink_Example1()

Worksheets("Example 1").Select
Range("A1").Select

ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'Main Sheet'!A1", TextToDisplay:="Main Sheet"

End Sub

VBA Hyperlinks Example 1-6

Run this code using the F5 key or manually. Then, it will create a hyperlink in cell A1 in the sheet “Example 1.”

VBA Hyperlinks Example 1-7

When you click on the hyperlink “Main Sheet,” it redirects to the main sheet.

VBA Hyperlinks Example 1-8

Hyperlinks of Multiple Sheets with Loops

We have seen creating a VBA hyperlink for one sheet. However, when we have many sheets, it isn’t easy to create a VBA hyperlink for each sheet with the same line of code.

Assume you have 11 worksheets, as shown in the below image.

VBA Hyperlinks Example 2

You want to create a hyperlink for each sheet in the Index sheet using VBA code.

Step 1: Define the variable as a worksheet.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

End Sub

Example 2-1

Step 2: The first thing is to select the worksheet Index and select cell A1.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

End Sub

Example 2-2

Step 3: Now, open For Each Loop in VBAVBA For Each Loop helps the user to inspect and analyze the groups of objects or values individually. It even facilitates performing the specific activity for every object or value by passing a statement or group of statements in this reference.read more.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

For Each Ws In ActiveWorkbook.Worksheets

Next Ws

End Sub

Example 2-3

Step 4: Since we have selected cell A1, it is now an active cell. So, start the hyperlink with the active cell.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

For Each Ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add(

Next Ws

End Sub

Example 2-4

Step 5: An anchor is a hyperlink cell. So, it is the active cell.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

For Each Ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell,

Next Ws

End Sub

VBA Hyperlinks Example 2-5

Step 6: Address is nothing mentioned it as “.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

For Each Ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell,Address:="",

Next Ws

End Sub

Example 2-6

Step 7: Subaddress: When we loop through the sheet, it should be the sheet name. To refer to the sheet name, we need a single quote, “’” with sheet name and “! Cell Address,” and close the sheet name with a single quote “’.”

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

For Each Ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell,Address:="",SubAddress:=""& Ws.Name&"!A1"&"",

Next Ws

End Sub

VBA Hyperlinks Example 2-7

Step 8: Ignore the screen tip. For text to display, you can enter the worksheet name.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

For Each Ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:="" & Ws.Name & "!A1" & "", ScreenTip:="", TextToDisplay:=Ws.Name
Next Ws

End Sub

Example 2-8

Step 9: To store the hyperlink of each sheet in a different cell, every time a hyperlink, one must create it for one sheet. We need to move down one cell from the active cell.

Code:

Sub Create_Hyperlink()

Dim Ws As Worksheet

Worksheets("Index").Select
Range("A1").Select

For Each Ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:="" & Ws.Name & "!A1" & "", ScreenTip:="", TextToDisplay:=Ws.Name
ActiveCell.Offset(1, 0).Select

Next Ws

End Sub

Example 2-9

It will create a hyperlink of all the sheets in the Index sheet. This code is dynamic whenever there is any addition or deletion of sheets. Therefore, we need to run this code to have an updated hyperlink.

VBA Hyperlinks Example 2-10

Recommended Articles

This article has been a guide to VBA Hyperlinks. Here, we learn how to create hyperlinks in the worksheet using VBA code to quickly move from one sheet to another, along with some simple to advanced examples. Below are some useful Excel articles related to VBA: –

  • Excel Find Links
  • VBA Today
  • Hyperlink Formula in Excel
  • Concatenate in VBA

Содержание

  1. Метод Hyperlinks.Add (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Примечания
  6. Пример
  7. Поддержка и обратная связь
  8. VBA Hyperlinks
  9. VBA Hyperlinks
  10. Add a Hyperlink with VBA
  11. Adding Text to Display with VBA
  12. Adding a ScreenTip with VBA
  13. Delete a Hyperlink with VBA
  14. Delete all the Hyperlinks in a Worksheet
  15. VBA Coding Made Easy
  16. Follow a Website Hyperlink Using VBA
  17. Follow a Hyperlink to a Folder on Your Drive
  18. Follow a Hyperlink to a File on Your Drive
  19. Go to a Cell in another sheet in the same Workbook
  20. Display all the Hyperlinks in a Worksheet
  21. Display all the Hyperlinks in a Workbook
  22. Using the FollowHyperlink Method to Create Emails
  23. Adding a Hyperlink to an AutoShape in Excel
  24. Inserting the Hyperlink Formula into a Cell Using VBA
  25. Adding a Hyperlink to a Button in Access
  26. Creating a Hyperlink from a Selection in Word
  27. VBA Code Examples Add-in
  28. VBA Excel. Метод Hyperlinks.Add (создание гиперссылки)
  29. Метод Hyperlinks.Add
  30. Синтаксис
  31. Параметры
  32. Создание гиперссылок
  33. Гиперссылка на другой лист
  34. Гиперссылка на любой файл
  35. Гиперссылка на интернет-сайт
  36. Поиск гиперссылок в диапазоне
  37. 12 комментариев для “VBA Excel. Метод Hyperlinks.Add (создание гиперссылки)”
  38. VBA Hyperlink
  39. Definition of VBA Hyperlink
  40. How to Create a Hyperlink in Excel Using VBA Code?
  41. Examples to Create Hyperlinks in Excel VBA
  42. Example #1 – Creating a hyperlink from the Worksheet to a website
  43. Example #2 – Hyperlink to Connect Two Worksheets
  44. Example #3 – Hyperlink with Multiple Worksheets
  45. Things to Remember
  46. Recommended Articles

Метод Hyperlinks.Add (Excel)

Добавляет гиперссылку к указанному диапазону или фигуре.

Синтаксис

expression.Add (Anchor, Address, SubAddress, ScreenTip, TextToDisplay)

выражение: переменная, представляющая объект Hyperlinks.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Anchor Обязательный Object Привязка для гиперссылки. Может быть либо объектом Range, либо объектом Shape.
Address Обязательный String Адрес гиперссылки.
SubAddress Необязательный Variant Субадрес гиперссылки.
ScreenTip Необязательный Variant Всплывающая подсказка, отображаемая при наведении указателя мыши на гиперссылку.
TextToDisplay Необязательный Variant Текст, отображаемый для гиперссылки.

Возвращаемое значение

Объект Hyperlink, представляющий новую гиперссылку.

Примечания

При указании аргумента TextToDisplay текст должен быть строкой.

Пример

В этом примере в ячейку A5 добавляется гиперссылка.

В этом примере в ячейку A5 добавляется гиперссылка на сообщение электронной почты.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Hyperlinks

In this Article

This VBA Tutorial covers the different ways to work with hyperlinks in VBA.

VBA Hyperlinks

With VBA, you can add hyperlinks, remove hyperlinks, create emails using hyperlinks, and open files using hyperlinks in VBA.

Add a Hyperlink with VBA

The Hyperlinks.Add Method adds a hyperlink to a cell using VBA.

The following code will add a hyperlink to cell A1:

Adding Text to Display with VBA

You can add neat user-friendly text to display to your hyperlink with VBA. If you used the worksheet functionality you would insert a hyperlink and then add a text to display in the dialog box provided.

The code below demonstrates how to add text to display to your hyperlink using VBA:

Adding a ScreenTip with VBA

You can add a ScreenTip to your hyperlink that the viewer will see when they hover over the link.

The code below shows how to add a ScreenTip to your hyperlink using VBA:

Delete a Hyperlink with VBA

The Hyperlinks.Delete Method can be used to delete a hyperlink from a cell.

The following code will delete the hyperlink from cell A1 and the text in the cell.

Note that just deleting the hyperlink, does not delete the text itself that’s why if you want the text deleted you also have to use the Clear method.

Delete all the Hyperlinks in a Worksheet

You can also delete all the hyperlinks in your worksheet using the Hyperlinks.Delete method.

The following code will delete all the hyperlinks in the first worksheet in your workbook:

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Follow a Website Hyperlink Using VBA

The following code allows you to open a website address, in a new window in your browser using the FollowHyperlink method in your workbook:

Follow a Hyperlink to a Folder on Your Drive

The following code will open a folder called ExcelFiles on the Desktop using the FollowHyperlink Method:

Follow a Hyperlink to a File on Your Drive

The following code will open an Excel file called WorkbookOne in the folder called ExcelFiles on the Desktop using the FollowHyperlink Method:

Go to a Cell in another sheet in the same Workbook

You can add a hyperlink to a cell in one sheet that takes you to another sheet, in the same workbook with VBA. Let’s say you are on Sheet1, cell A1 of your workbook and you want to insert a hyperlink to Sheet2, cell B2 of the same workbook, you can use the SubAddress property to do this.

The following code demonstrates how to do this:

Display all the Hyperlinks in a Worksheet

You can access the hyperlinks collection and display all the hyperlinks in your worksheet in the Intermediate window in the VBA Editor. You must first press CTRL+G on your keyboard or go to View>Intermediate Window in the VBE Editor, to view the Intermediate Window.

The following code shows how to view the hyperlinks in your worksheet in the Intermediate Window:

The results are shown in the Intermediate Window.

Display all the Hyperlinks in a Workbook

You can access the hyperlinks collection, to loop through and display all the hyperlinks in your Workbook in a Message Box.

The following code shows how to do this, and uses a nested loop in order to achieve this:

Using the FollowHyperlink Method to Create Emails

You can also create emails using the FollowHyperlink Method.

The code below will show you how to create emails using the FollowHyperlink Method in VBA:

Adding a Hyperlink to an AutoShape in Excel

You can add a hyperlink to an Autoshape in Excel so that when the user clicks on the shape they get taken to a website address.

The following code creates a rounded rectangle, adds the text to the rectangle and adds a hyperlink to the rectangle:

The result is:

Inserting the Hyperlink Formula into a Cell Using VBA

Let’s say you have a post title in cell A4 and a post link in cell B4 as shown in the image below.

A quick reminder of the worksheet Hyperlink formula syntax is:

link_location – This is the link to the document, file, place in the workbook or online site.

friendly_name – (Optional) – The text or numeric value that is displayed in the cell.

In cell C4, you want to add the hyperlink with a friendly text to display, now usually you would enter the formula =HYPERLINK(B4,A4) in C4 to get the following:

You could instead use VBA to achieve the same result, and insert this formula in the cell, on Sheet1 with the following code:

Adding a Hyperlink to a Button in Access

VBA allows you to work with hyperlinks in Access too. Let’s say we have a button on a form and when the user clicks on that button we want them to be taken to a website. One way that you can use to do this, is through the Application.FollowHyperlink method.

We have our sample form with a button called buttonOne shown below.

The code for this button would be:

Creating a Hyperlink from a Selection in Word

You can work with hyperlinks in Word VBA as well.
Let’s say we have text in Word that says “Click Here to Be Taken to the Automate Excel Website”, that is selected as shown below.

To turn this text into a hyperlink using VBA, you can use the following code:

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Создание гиперссылки в VBA Excel методом Hyperlinks.Add для перехода на другой лист, на интернет-сайт, для открытия любого файла в программе по умолчанию.

Метод Hyperlinks.Add

Синтаксис

Expression — выражение (переменная), возвращающее объект Hyperlinks.

Параметры

Параметр Описание
Anchor Объект Range или объект Shape, к которому привязывается (добавляется) новая гиперссылка. Обязательный параметр. Тип данных — Object.
Address Адрес гиперссылки. Обязательный параметр. Тип данных — String.
SubAddress Субадрес гиперссылки. Необязательный параметр. Тип данных — Variant.
ScreenTip Всплывающая подсказка, отображаемая при наведении указателя мыши на текст гиперссылки. Необязательный параметр. Тип данных — Variant.
TextToDisplay Текст гиперссылки. Необязательный параметр. Тип данных — Variant.

Если текст гиперссылки (TextToDisplay) не указан, будет отображен текст параметров Address и SubAddress.

Создание гиперссылки на рабочий лист другой книги:

Создание гиперссылки на другой лист текущей книги:

Создание гиперссылки на другую ячейку того же листа:

Создание гиперссылки на документ Word:

Создание гиперссылки на точечный рисунок:

Пример добавления гиперссылки на рубрику «VBA Excel» сайта «Время не ждёт»:

Поиск первой ячейки с гиперссылкой в заданном диапазоне:

Для поиска последней ячейки с гиперссылкой в заданном диапазоне следует заменить строку
For i = 1 To n
на
For i = n To 1 Step -1 .

12 комментариев для “VBA Excel. Метод Hyperlinks.Add (создание гиперссылки)”

Здравствуйте, Евгений.
Подскажите пожалуйста, как можно определить адрес ячейки, которая содержит гиперссылку? А если ячеек с гиперссылками несколько, то как определить адрес последней (нижней правой) из них?

Здравствуйте, Юрий!
Ответ добавил в конец статьи.

Добрый день!
Скажите, пожалуйста, как сделать, чтобы в переменную Address:= вставлять не конкретный адрес, а скопированную ссылку из буфера обмена?
Заранее спасибо!

Решил проблему вот так вот:

Добрый день!
У меня в очередной раз «зачудила» книга Excell. Сама поменяла родные адреса гиперссылок в Инет во многих ячейках на один, которые понравившейся ей, меняя лишь концовку 1649, 1650, …. .
В отладчике VBA вышел на этот список подмены: Range(«L10»). Hyperlinks.Items 1.Formyla[1…5] содержащий 5 вставляемых ею адресов. В VBA не удалось добраться до этих формул.
Скажите, пожалуйста, можно ли программно восстановить стоящие ранее адреса? И как это сделать? И можно ли ей запретить так своевольничать?

Здравствуйте, Павел!
Я не знаю, как восстановить предыдущую версию файла Excel. Есть что-то у разработчиков, но это не программно.
Код, который перезаписывает гиперссылки, поищите в модулях книги и листа. Процедуры, размещенные в этих модулях, могут запускаться самостоятельно при совершении определенных событий, к которым они привязаны.

Здравствуйте, Евгений!
Спасибо за ответ. Отрицательный ответ, когда книга шибко нужна, лишь стимулирует поиск решения. Буду делать ей “костыли”, гиперссылки превращу в обычный текст и, как лучший вариант, хотел бы запускать их программно без привязки к конкретной ячейке конкретного листа конкретной книги.
Скажите, пожалуйста, есть ли возможность программно запускать гиперссылку на открытие страницы в Инете? Без привязки к конкретной ячейке.

Здравствуйте, Павел!
Открыть страницу сайта можно методом FollowHyperlink. Этот метод может не работать в старых версиях Excel.

Здравствуйте, Евгений!
Спасибо за ответ. Предложенный Вами метод работает в моей версии.

Источник

VBA Hyperlink

Definition of VBA Hyperlink

The hyperlink is commonly used with websites for navigating from one page to another or one website to another on the internet. In a similar way, we can control the movements within excel worksheet too. The different operations that can be performed in Excel are:

  • Moving to a specific location within the current workbook.
  • Opening different documents and select a mentioned area within the document.
  • Navigating to webpages from the worksheet.
  • Sending email to a defined address.

The hyperlink is easy to recognize because of its color change, mostly in blue. There exist different methods to create a hyperlink in excel and let using VBA.

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

How to Create a Hyperlink in Excel Using VBA Code?

You can add a hyperlink to a text or one sheet to another worksheet within excel using hyperlink add property. The format needs to be followed by specifying where the hyperlink should be created and navigation URL etc.

Format for VBA Hyperlink Add

The format shows the parameters need to be provided to add a hyperlink to a worksheet.

  • Anchor: Defines the cell you want to create the hyperlink.
  • Address: The URL to which the navigation should move.
  • [SubAddress]: Subaddress of the URL.
  • [ScreenTip]: The mouse pointer value to be showed while placing a mouse pointer.
  • [Text to Display]: The text needs to be displayed on the cell.

Use the Active cell property to add a hyperlink.

Select the add method from the list

Examples to Create Hyperlinks in Excel VBA

Below are the different examples to create hyperlinks in excel using VBA code.

Example #1 – Creating a hyperlink from the Worksheet to a website

We want to create a hyperlink from worksheet named sub to a website using VBA code in excel.

Below are the steps to create a hyperlink in Excel VBA:

Step 1: Create a function named hyper to add the hyperlink.

Code:

Step 2: Use the Active cell object to get open the hyperlink add method.

Code:

Step 3: Provide the parameter values to the hyperlink add method.

Code:

  • Anchor: name of the worksheet
  • Address: Hyperlink to where the control to be navigated, given the website address
  • ScreenTip: The mouse pointer text
  • TextToDisplay: To which text the hyperlink is to be assigned

Step 4: Hit F5 or Run button under VBE to run this code and see the output.

The cell range A1 is selected and the text is assigned with a hyperlink, once you click on the text “Excel Training” it will redirect to the website https://www.educba.com/. When you move the mouse pointer next to the text it will show the mouse pointer text.

Example #2 – Hyperlink to Connect Two Worksheets

We have two worksheets named Home and sub. Let’s try to create a hyperlink from sub to home using VBA code.

Follow the below steps to create a hyperlink from one worksheet to another within the same workbook using the VBA code.

Step 1: Create a function, where we will write all codes to perform the action. Write code to select the worksheet ‘sub’ using the selection method of the worksheet.

Code:

Since the control moves within the sheet, it is necessary to select the worksheet in which you are creating the hyperlink.

Step 2: Select the cell range within the sheet where the hyperlink is want to create.

Code:

Step 3: Now let’s add the hyperlink using the active cell property.

Code:

Since the worksheet is already selected, Anchor is given as ‘Selection’. The hyperlink is specified as ‘Home’ sheet and range A1.

Step 4: Run the code and sheet sub will be shown the hyperlink as below.

Step 5: Once the text is clicked the control will be moved to the ‘Home’ sheet. And cell A1 will be selected.

Example #3 – Hyperlink with Multiple Worksheets

If you want to create hyperlink across multiple worksheets it is also possible. In this example, we have multiple sheets within the same workbook. Different type of excel functions exists so from the main worksheet ‘Functions’. Let’s try to create a hyperlink to the different worksheet named with different functions using VBA code:

The multiple worksheets are named as below with different excel function names

Since we want to create a hyperlink to each worksheet it’s difficult to repeat the code. Follow the below steps to create a hyperlink using VBA Code in Excel:

Step 1: Create a variable to deal with worksheet easily.

Code:

Step 2: Now we want to select the main page which acts as an index page and select the cell range A1.

Code:

Step 3: To move through multiple worksheet and hyperlink we are creating a for each loop. A1 is already selected as active cell so creating a hyperlink from this.

Code:

Step 4: Provide the parameter values to create a hyperlink for each worksheet. Since hyperlink starts from active cell anchor=Active cell, the address is given as ” “.

Code:

Step 5: The hyperlink is looped through worksheet so we should give subaddress as sheet names. To get the sheet names we can use the variable ws and cell range as A1. The sheet name will have referred with a single quotation. Sheet name and range will be specified and also closed with a single quotation.

Code:

Step 6: To get the hyperlink with sheet name gives TextToDisplay as ws.Name

Code:

This code will store hyperlink for each worksheet in the same cell A1.

Step 7: To change this each sheet to different cell down one cell from the active cell.

Code:

Step 8: Run the program and each sheet name will be displayed on the sheet ‘Functions’ and while clicking on it the control will move to the corresponding sheet.

Things to Remember

  • Hyperlink property of active cell used to create hyperlinks in VBA.
  • Hyperlink help to move within the workbook easily.

Recommended Articles

This is a guide to VBA Hyperlinks. Here we learn how to create hyperlinks in Worksheet Using VBA Code to quickly move from one sheet to another sheet along with some practical examples and downloadable excel template . You can also go through our other suggested articles –

Источник

VBA Hyperlink

Definition of VBA Hyperlink

The hyperlink is commonly used with websites for navigating from one page to another or one website to another on the internet. In a similar way, we can control the movements within excel worksheet too. The different operations that can be performed in Excel are:

  • Moving to a specific location within the current workbook.
  • Opening different documents and select a mentioned area within the document.
  • Navigating to webpages from the worksheet.
  • Sending email to a defined address.

The hyperlink is easy to recognize because of its color change, mostly in blue. There exist different methods to create a hyperlink in excel and let using VBA.

How to Create a Hyperlink in Excel Using VBA Code?

You can add a hyperlink to a text or one sheet to another worksheet within excel using hyperlink add property. The format needs to be followed by specifying where the hyperlink should be created and navigation URL etc.

Format for VBA Hyperlink Add

Syntax of VBA hyperlink add

The format shows the parameters need to be provided to add a hyperlink to a worksheet.

  • Anchor: Defines the cell you want to create the hyperlink.
  • Address: The URL to which the navigation should move.
  • [SubAddress]: Subaddress of the URL.
  • [ScreenTip]: The mouse pointer value to be showed while placing a mouse pointer.
  • [Text to Display]: The text needs to be displayed on the cell.

Use the Active cell property to add a hyperlink.

VBA Hyperlink 1

Select the add method from the list

VBA Hyperlink 2

Examples to Create Hyperlinks in Excel VBA

Below are the different examples to create hyperlinks in excel using VBA code.

You can download this VBA Hyperlink Excel Template here – VBA Hyperlink Excel Template

Example #1 – Creating a hyperlink from the Worksheet to a website

We want to create a hyperlink from worksheet named sub to a website using VBA code in excel.

Below are the steps to create a hyperlink in Excel VBA:

Step 1: Create a function named hyper to add the hyperlink.

Code:

Private Sub hyper()

End Sub

VBA Hyperlink Example 1-1

Step 2: Use the Active cell object to get open the hyperlink add method.

Code:

Private Sub hyper()

ActiveCell.Hyperlinks.Add(

End Sub

VBA Hyperlink Example 1-2

Step 3: Provide the parameter values to the hyperlink add method.

Code:

Private Sub hyper()

ActiveCell.Hyperlinks.Add Anchor:=Sheets("sub").Range("A1"), Address:="https://www.educba.com/", SubAddress:="", ScreenTip:="it is a Hyperlink", TextToDisplay:="Excel Training"

End Sub
  • Anchor: name of the worksheet
  • Address: Hyperlink to where the control to be navigated, given the website address
  • ScreenTip: The mouse pointer text
  • TextToDisplay: To which text the hyperlink is to be assigned

Step 4: Hit F5 or Run button under VBE to run this code and see the output.

Result of Example 1-3

The cell range A1 is selected and the text is assigned with a hyperlink, once you click on the text “Excel Training” it will redirect to the website https://www.educba.com/. When you move the mouse pointer next to the text it will show the mouse pointer text.

VBA Hyperlink Example 1-4

Example #2 – Hyperlink to Connect Two Worksheets

We have two worksheets named Home and sub. Let’s try to create a hyperlink from sub to home using VBA code.

Two Worksheets

Follow the below steps to create a hyperlink from one worksheet to another within the same workbook using the VBA code.

Step 1: Create a function, where we will write all codes to perform the action. Write code to select the worksheet ‘sub’ using the selection method of the worksheet.

Code:

Private Sub hyper1()

Worksheets("sub").Select

End Sub

VBA Hyperlink Example 2-2

Since the control moves within the sheet, it is necessary to select the worksheet in which you are creating the hyperlink.

Step 2: Select the cell range within the sheet where the hyperlink is want to create.

Code:

Private Sub hyper1()

Worksheets("sub").Select
Range("A1").Select

End Sub

VBA Hyperlink Example 2-3

Step 3: Now let’s add the hyperlink using the active cell property.

Code:

Private Sub hyper1()

Worksheets("sub").Select
Range("A1").Select
ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'Home'!A1", TextToDisplay:="Click to move home sheet"

End Sub

VBA Hyperlink Example 2-4

Since the worksheet is already selected, Anchor is given as ‘Selection’. The hyperlink is specified as ‘Home’ sheet and range A1.

Step 4: Run the code and sheet sub will be shown the hyperlink as below.

Result of Example 2-5

Step 5: Once the text is clicked the control will be moved to the ‘Home’ sheet. And cell A1 will be selected.

Result of Example 2-6

Example #3 – Hyperlink with Multiple Worksheets

If you want to create hyperlink across multiple worksheets it is also possible. In this example, we have multiple sheets within the same workbook. Different type of excel functions exists so from the main worksheet ‘Functions’. Let’s try to create a hyperlink to the different worksheet named with different functions using VBA code:

The multiple worksheets are named as below with different excel function names

Multiple Worksheets

Since we want to create a hyperlink to each worksheet it’s difficult to repeat the code. Follow the below steps to create a hyperlink using VBA Code in Excel:

Step 1: Create a variable to deal with worksheet easily.

Code:

Private Sub hyper2()

Dim ws As Worksheet

End Sub

VBA Hyperlink Example 3-2

Step 2: Now we want to select the main page which acts as an index page and select the cell range A1.

Code:

Private Sub hyper2()

Dim ws As Worksheet
Worksheets("Functions").Select
Range("A1").Select

End Sub

VBA Hyperlink Example 3-3

Step 3: To move through multiple worksheet and hyperlink we are creating a for each loop. A1 is already selected as active cell so creating a hyperlink from this.

Code:

Private Sub hyper2()

Dim ws As Worksheet
Worksheets("Functions").Select
Range("A1").Select

For Each ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell
Next ws

End Sub

VBA Hyperlink Example 3-4

Step 4: Provide the parameter values to create a hyperlink for each worksheet. Since hyperlink starts from active cell anchor=Active cell, the address is given as ” “.

Code:

Private Sub hyper2()

Dim ws As Worksheet
Worksheets("Functions").Select
Range("A1").Select

For Each ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:=""
Next ws

End Sub

VBA Hyperlink Example 3-5

Step 5: The hyperlink is looped through worksheet so we should give subaddress as sheet names. To get the sheet names we can use the variable ws and cell range as A1. The sheet name will have referred with a single quotation. Sheet name and range will be specified and also closed with a single quotation.

Code:

Private Sub hyper2()

Dim ws As Worksheet
Worksheets("Functions").Select
Range("A1").Select

For Each ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:="" & ws.Name & "!A1" & ""
Next ws

End Sub

VBA Hyperlink Example 3-6

Step 6: To get the hyperlink with sheet name gives TextToDisplay as ws.Name

Code:

Private Sub hyper2()

Dim ws As Worksheet
Worksheets("Functions").Select
Range("A1").Select

For Each ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:="" & ws.Name & "!A1" & "", TextToDisplay:=ws.Name
Next ws

End Sub

VBA Hyperlink Example 3-7

This code will store hyperlink for each worksheet in the same cell A1.

Step 7: To change this each sheet to different cell down one cell from the active cell.

Code:

Private Sub hyper2()

Dim ws As Worksheet
Worksheets("Functions").Select
Range("A1").Select

For Each ws In ActiveWorkbook.Worksheets
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:="" & ws.Name & "!A1" & "", TextToDisplay:=ws.Name
ActiveCell.Offset(1, 0).Select
Next ws

End Sub

VBA Hyperlink Example 3-8

Step 8: Run the program and each sheet name will be displayed on the sheet ‘Functions’ and while clicking on it the control will move to the corresponding sheet.

Result of Example 3-9

Things to Remember

  • Hyperlink property of active cell used to create hyperlinks in VBA.
  • Hyperlink help to move within the workbook easily.

Recommended Articles

This is a guide to VBA Hyperlinks. Here we learn how to create hyperlinks in Worksheet Using VBA Code to quickly move from one sheet to another sheet along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Loops
  2. VBA RGB
  3. VBA Break for Loop
  4. VBA XML

Понравилась статья? Поделить с друзьями:
  • Vba for excel inputbox
  • Vba getopenfilename excel files
  • Vba for excel functions
  • Vba get data from excel
  • Vba from excel to word table