Vba excel ссылка на сайт

Создание гиперссылки в 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

How to open a website in the browser from Excel using a Macro and VBA.

This is the same as following a link or clicking a link from the worksheet except that it will be done through a Macro.

This does not open a website within Excel. Everything will still open in the browser.

The Macro

Here is the full macro that you need:

Sub Go_to_Website()

Dim ie As Object

Set ie = CreateObject("INTERNETEXPLORER.APPLICATION")

ie.NAVIGATE "http://www.google.com"

ie.Visible = True

While ie.busy

 DoEvents

Wend

End Sub

This is a simple macro and it will open the website into Internet Explorer by default.

To use the macro, change http://www.google.com to whatever website you want the user to visit.

You can also replace this with a variable that holds the website url in order to make this a bit more versatile. In that case, you would just replace «http://www.google.com» with the desired variable name and without the double quotation marks around the variable name.

This is a fairly simple macro and you should not need to change anything other than what I just mentioned.

If you don’t know how to put this macro into Excel, you can read this tutorial here: Install a Macro into Excel

Make sure to download the sample file attached to this tutorial so you can get the macro ready to go in Excel.


Excel VBA Course

Excel VBA Course — From Beginner to Expert

200+ Video Lessons
50+ Hours of Instruction
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Similar Content on TeachExcel

Open any Program from Excel

Macro: This free excel macro allows you to open any program on your computer from excel. You…

Login to a Website using a Macro

: Connect and login to a website using a macro in Excel.
This allows you to open a website a…

Open Microsoft Outlook from Excel

Macro: This free macro will open the Microsoft Outlook program on your computer. You do need…

Open Microsoft Word from Excel

Macro: This free macro will open the Microsoft Word program on your computer. You do need to have…

Open Microsoft PowerPoint from Excel

Macro: This free macro will open the Microsoft PowerPoint program on your computer. You do need t…

Make Users Enable Macros in Order to View a Workbook in Excel

Tutorial: Tutorial showing you how to make a user enable macros in a workbook in order to view the w…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Excel VBA Course

Excel VBA Course — From Beginner to Expert

200+ Video Lessons

50+ Hours of Video

200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Содержание

  1. Метод Hyperlinks.Add (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Примечания
  6. Пример
  7. Поддержка и обратная связь
  8. Что такое гиперссылка?
  9. VBA Hyperlink
  10. Definition of VBA Hyperlink
  11. How to Create a Hyperlink in Excel Using VBA Code?
  12. Examples to Create Hyperlinks in Excel VBA
  13. Example #1 – Creating a hyperlink from the Worksheet to a website
  14. Example #2 – Hyperlink to Connect Two Worksheets
  15. Example #3 – Hyperlink with Multiple Worksheets
  16. Things to Remember
  17. 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 и обратная связь.

Источник

Гиперссылка — это не просто отображение адреса на ресурс — это активная ссылка, кликнув на которую может быть открыта

  • интернет-страница в браузере по умолчанию
  • локальный файл на текущем ПК или файл на подключенном сетевом диске
  • директория(папка) на локальном ПК или подключенном сетевом диске

Установить гиперссылку можно несколькими способами: через стандартное меню и путем создания функции.

СТАНДАРТНОЕ МЕНЮ
и самый распространенный: правый клик мыши по ячейке — Гиперссылка (Hyperlink) (или вкладка Вставка (Insert)Ссылка (Hyperlink) . Откроется окно добавления гиперссылки.

Там можно выбрать вид ссылки:

  • на файл или веб-страницу . Если на веб-страницу, то необходимо в поле «Адрес» указать адрес веб-страницы. Если ссылка на файл — просто выбрать файл в диспетчере файлов.
  • местом в документе . Выбирается необходимый лист и адрес ячейки, на которую необходимо переместиться по нажатии гиперссылки.
  • новым документом . Создается новый документ и сразу ссылка на него. При нажатии гиперссылки будет открыт этот файл.
  • электронной почтой . Указывается адрес электронной почты и тема письма по умолчанию. По нажатии ссылки будет создано письмо на указанный адрес электронной почты и с указанной темой.

Самый серьезный недостаток этого метода в том, что после сортировки таблиц со множеством таких гиперссылок они неизбежно «ломаются», т.е. перестают работать.

Создание гиперссылки кодом VBA выглядит следующим образом:

ActiveSheet.Hyperlinks.Add Anchor:=Range(«A1″), _ Address:=»http://www.excel-vba.ru/», _ TextToDisplay:=»Перейти на сайт http://www.excel-vba.ru/»

Данный код создаст в ячейке A1 активного листа гиперссылку на сайт http://www.excel-vba.ru/.

  • Range(«A1») — это ячейка, в которой будет создана гиперссылка
  • Address(http://www.excel-vba.ru/) — адрес страницы(или путь к файлу или директории), который будет открыт по клике на ячейку
  • TextToDisplay(Перейти на сайт http://www.excel-vba.ru/) — это текст, который будет отображаться в ячейке. Может отличаться от адреса самой ссылки

ФУНКЦИЯ ЛИСТА
Гиперссылки можно создавать на листе через одноименную функцию ГИПЕРССЫЛКА (HYPERLINK) . Функция расположена в категории Ссылки и массивы диспетчера функций. Такой способ очень удобен, если необходимо создать много гиперссылок на листе.
Синтаксис функции:
=ГИПЕРССЫЛКА(» www.excel-vba.ru «;» переход на сайт «)
=HYPERLINK(«www.excel-vba.ru»;»переход на сайт»)

  • www.excel-vba.ru — адрес страницы(или путь к файлу или директории), который будет открыт по клике на ячейку
  • переход на сайт — текст, который будет отображаться в ячейке. Может отличаться от текста самой ссылки

Конечно, универсальность создания гиперссылок через функцию именно в том, что можно в отдельном столбце записать адреса интернет-страниц, а в другой просто создать на них ссылки. Допустим, если в столбце А у нас ссылки, то в столбец В мы можем записать и протянуть такую формулу:
=ГИПЕРССЫЛКА(A1;»переход на сайт»)
Или другой вариант: у нас есть адреса сайта(для примера возьмем этот: «https://www.excel-vba.ru/» ), а в столбце А указаны только адреса страниц, без указания домена. Что-то вроде «kak-excel-vosprinimaet-dannye» . Т.е. нам необходимо объединить основной адрес с дополнительным. Тогда можно записать так:
=ГИПЕРССЫЛКА(«https://www.excel-vba.ru/» & A1 ;»переход на страницу сайта»)
Теперь при клике на ячейку откроется страница https://www.excel-vba.ru/kak-excel-vosprinimaet-dannye.
А можно сделать еще универсальнее — записать вдобавок адрес сайта не статично внутри функции, а в отдельной ячейке. Пусть это будет ячейка D1. Тогда функция будет выглядеть так:
=ГИПЕРССЫЛКА( $D$1 & A1 ;»переход на страницу сайта»)
Важно учитывать слеши в ячейках. Т.е. если в D1 записан адрес домена без слеша на конце( «https://www.excel-vba.ru/» ), то его необходимо будет учесть либо в адресах страниц( «/kak-excel-vosprinimaet-dannye» ), либо напрямую в функции:
=ГИПЕРССЫЛКА( $D$1 & «/» & A1 ;»переход на страницу сайта»)
Нетрудно догадаться, что таких ссылок можно создать множество простым копированием формулы в другие ячейки и что немаловажно — в столбце А можно записывать разные окончания ссылок. Если вдруг сайт поменял адрес, но система ссылок осталась прежней — надо будет лишь заменить основной адрес. То же самое можно отнести и к файлам на диске: если поменялась лишь корневая директория — то просто меняем её в функции или в ячейке.

ГИПЕРССЫЛКА на конкретную ячейку листа
Так же можно создать гиперссылку, переходящую на определенную ячейку на листе:
=ГИПЕРССЫЛКА(» # Лист2!D4″;»Перейти в ячейку D4 Лист2″)
Обращаю особое внимание на знак решетки(#) перед именем листа — в данном случае он обязателен, т.к. указывает функции, что переход будет осуществляться внутри листов книги, в которой записана гиперссылка.
Ссылку на ячейку можно указывать динамически, ссылаясь на определенную ячейку, не вписывая её адрес(на примере D4 ):
=ГИПЕРССЫЛКА(«#Лист2!» & D4);»Перейти в ячейку «&D4&» Лист2″)
Или более классическая ситуация — в столбце А у нас записаны имена листов, а в столбце В нам необходимо сделать гиперссылки на ячейку D4 отдельно для каждого листа. Иными словами — оглавление. Тогда в ячейку В1 запишем функцию:
=ГИПЕРССЫЛКА(«# «& A1 &» !D4″);»Перейти на лист»)

Важно: Обращаю внимание на функцию выше — она несколько отличается от приведенных ранее. Если в имени листа содержатся пробелы(или иные знаки препинания, кроме точки и нижнего подчеркивания), то обязательно после знака решетки и перед восклицательным знаком ставить знаки апострофа( )
«# Москва Январь !D4″
Если для таких ссылок не указать апостроф, то получим ошибку «Неверная ссылка».
Если же пробелов и иных символов в имени листа нет — указание апострофа не вызовет ошибку. Поэтому для подстраховки, в подобных случаях правильнее всегда указывать апострофы, чтобы избежать неверных ссылок.

Важно: Если в имени книги или листа содержатся пробелы(или иные знаки препинания, кроме точки и нижнего подчеркивания), то обязательно после знака решетки и перед восклицательным знаком ставить апостроф(‘). Я специально в функции выше привел пример именно с пробелом(Продажи 2011.xls) — для наглядности.
При этом, как уже упоминал выше — неважно, пробел в имени листа или книги:
=ГИПЕРССЫЛКА(«# [Продажи.xls]Москва Январь !D4″);»Перейти в ячейку D4″)
И если не уверены в том, будет ли имя листа и книги содержать такие символы(например, если адрес для перехода составляется из ссылок на другие ячейки) — лучше в формуле проставлять апострофы всегда. Ошибкой это не будет и гиперссылка будет работать, даже если таких символов в имени не окажется.

ГИПЕРССЫЛКА для открытия файла
При помощи функции ГИПЕРССЫЛКА так же можно указать путь к файлу, который необходимо открыть по нажатии ячейки:
=ГИПЕРССЫЛКА(«C:UsersДмитрийDesktopКнига 1.xls»;»Открыть книгу Книга 1.xls»)
Путь должен быть корректным, а имя файла необходимо указывать с расширением.

Ложка дегтя
В качестве адреса для функции ГИПЕРССЫЛКА нельзя применить и открытие книги и одновременный переход на нужный лист и ячейку этой книги. Т.е. нельзя указать что-то вроде:
=ГИПЕРССЫЛКА(«C:UsersДмитрийDesktopКнига1.xls#Лист2!D4″;»Открыть книгу Книга 1.xls»)
Это связано с ограничением именно самой функции и на момент написания статьи точно не работало.

Статья помогла? Поделись ссылкой с друзьями!

Источник

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 –

Источник

Хитрости »

30 Май 2011              106754 просмотров


Что такое гиперссылка?

Гиперссылка — это не просто отображение адреса на ресурс — это активная ссылка, кликнув на которую может быть открыта

  • интернет-страница в браузере по умолчанию
  • локальный файл на текущем ПК или файл на подключенном сетевом диске
  • директория(папка) на локальном ПК или подключенном сетевом диске

Установить гиперссылку можно несколькими способами: через стандартное меню и путем создания функции.

СТАНДАРТНОЕ МЕНЮ

и самый распространенный: правый клик мыши по ячейке —

Гиперссылка(Hyperlink)

(или вкладка

Вставка(Insert)

Ссылка(Hyperlink)

. Откроется окно добавления гиперссылки.

Там можно выбрать вид ссылки:

  • на файл или веб-страницу. Если на веб-страницу, то необходимо в поле «Адрес» указать адрес веб-страницы. Если ссылка на файл — просто выбрать файл в диспетчере файлов.
  • местом в документе. Выбирается необходимый лист и адрес ячейки, на которую необходимо переместиться по нажатии гиперссылки.
  • новым документом. Создается новый документ и сразу ссылка на него. При нажатии гиперссылки будет открыт этот файл.
  • электронной почтой. Указывается адрес электронной почты и тема письма по умолчанию. По нажатии ссылки будет создано письмо на указанный адрес электронной почты и с указанной темой.

Самый серьезный недостаток этого метода в том, что после сортировки таблиц со множеством таких гиперссылок они неизбежно «ломаются», т.е. перестают работать.

Создание гиперссылки кодом VBA

выглядит следующим образом:

ActiveSheet.Hyperlinks.Add Anchor:=Range("A1"), _
                               Address:="http://www.excel-vba.ru/", _
                               TextToDisplay:="Перейти на сайт http://www.excel-vba.ru/"

Данный код создаст в ячейке A1 активного листа гиперссылку на сайт http://www.excel-vba.ru/.

  • Range(«A1») — это ячейка, в которой будет создана гиперссылка
  • Address(http://www.excel-vba.ru/) — адрес страницы(или путь к файлу или директории), который будет открыт по клике на ячейку
  • TextToDisplay(Перейти на сайт http://www.excel-vba.ru/) — это текст, который будет отображаться в ячейке. Может отличаться от адреса самой ссылки

ФУНКЦИЯ ЛИСТА

Гиперссылки можно создавать на листе через одноименную функцию

ГИПЕРССЫЛКА (HYPERLINK)

. Функция расположена в категории Ссылки и массивы диспетчера функций. Такой способ очень удобен, если необходимо создать много гиперссылок на листе.

Синтаксис функции:
=ГИПЕРССЫЛКА(«www.excel-vba.ru»;»переход на сайт»)
=HYPERLINK(«www.excel-vba.ru»;»переход на сайт»)

  • www.excel-vba.ru — адрес страницы(или путь к файлу или директории), который будет открыт по клике на ячейку
  • переход на сайт — текст, который будет отображаться в ячейке. Может отличаться от текста самой ссылки

Конечно, универсальность создания гиперссылок через функцию именно в том, что можно в отдельном столбце записать адреса интернет-страниц, а в другой просто создать на них ссылки. Допустим, если в столбце А у нас ссылки, то в столбец В мы можем записать и протянуть такую формулу:
=ГИПЕРССЫЛКА(A1;»переход на сайт»)
Или другой вариант: у нас есть адреса сайта(для примера возьмем этот: «https://www.excel-vba.ru/»), а в столбце А указаны только адреса страниц, без указания домена. Что-то вроде «kak-excel-vosprinimaet-dannye». Т.е. нам необходимо объединить основной адрес с дополнительным. Тогда можно записать так:
=ГИПЕРССЫЛКА(«https://www.excel-vba.ru/»&A1;»переход на страницу сайта»)
Теперь при клике на ячейку откроется страница https://www.excel-vba.ru/kak-excel-vosprinimaet-dannye.
А можно сделать еще универсальнее — записать вдобавок адрес сайта не статично внутри функции, а в отдельной ячейке. Пусть это будет ячейка D1. Тогда функция будет выглядеть так:
=ГИПЕРССЫЛКА($D$1&A1;»переход на страницу сайта»)
Важно учитывать слеши в ячейках. Т.е. если в D1 записан адрес домена без слеша на конце(«https://www.excel-vba.ru/»), то его необходимо будет учесть либо в адресах страниц(«/kak-excel-vosprinimaet-dannye»), либо напрямую в функции:
=ГИПЕРССЫЛКА($D$1&«/»&A1;»переход на страницу сайта»)
Нетрудно догадаться, что таких ссылок можно создать множество простым копированием формулы в другие ячейки и что немаловажно — в столбце А можно записывать разные окончания ссылок. Если вдруг сайт поменял адрес, но система ссылок осталась прежней — надо будет лишь заменить основной адрес. То же самое можно отнести и к файлам на диске: если поменялась лишь корневая директория — то просто меняем её в функции или в ячейке.

ГИПЕРССЫЛКА на конкретную ячейку листа
Так же можно создать гиперссылку, переходящую на определенную ячейку на листе:
=ГИПЕРССЫЛКА(«#Лист2!D4″;»Перейти в ячейку D4 Лист2»)
Обращаю особое внимание на знак решетки(#) перед именем листа — в данном случае он обязателен, т.к. указывает функции, что переход будет осуществляться внутри листов книги, в которой записана гиперссылка.
Ссылку на ячейку можно указывать динамически, ссылаясь на определенную ячейку, не вписывая её адрес(на примере D4):
=ГИПЕРССЫЛКА(«#Лист2!»&D4);»Перейти в ячейку «&D4&» Лист2″)
Или более классическая ситуация — в столбце А у нас записаны имена листов, а в столбце В нам необходимо сделать гиперссылки на ячейку D4 отдельно для каждого листа. Иными словами — оглавление. Тогда в ячейку В1 запишем функцию:
=ГИПЕРССЫЛКА(«#«&A1&«!D4″);»Перейти на лист»)

Важно: Обращаю внимание на функцию выше — она несколько отличается от приведенных ранее. Если в имени листа содержатся пробелы(или иные знаки препинания, кроме точки и нижнего подчеркивания), то обязательно после знака решетки и перед восклицательным знаком ставить знаки апострофа()
«#Москва Январь!D4″
Если для таких ссылок не указать апостроф, то получим ошибку «Неверная ссылка».
Если же пробелов и иных символов в имени листа нет — указание апострофа не вызовет ошибку. Поэтому для подстраховки, в подобных случаях правильнее всегда указывать апострофы, чтобы избежать неверных ссылок.


Можно так же переходить на ячейки листа в другой книге:

=ГИПЕРССЫЛКА(«#[Продажи 2011.xls]Москва!D4″;»Перейти в книгу продаж — на лист Москва»)

Здесь есть существенное ограничение: книга, на которую ссылается функция ГИПЕРССЫЛКА, должна быть открыта. И обязательно должна быть заключена в квадратные скобки, как в примере выше.

Важно: Если в имени книги или листа содержатся пробелы(или иные знаки препинания, кроме точки и нижнего подчеркивания), то обязательно после знака решетки и перед восклицательным знаком ставить апостроф(‘). Я специально в функции выше привел пример именно с пробелом(Продажи 2011.xls) — для наглядности.
При этом, как уже упоминал выше — неважно, пробел в имени листа или книги:
=ГИПЕРССЫЛКА(«#[Продажи.xls]Москва Январь!D4″);»Перейти в ячейку D4″)
И если не уверены в том, будет ли имя листа и книги содержать такие символы(например, если адрес для перехода составляется из ссылок на другие ячейки) — лучше в формуле проставлять апострофы всегда. Ошибкой это не будет и гиперссылка будет работать, даже если таких символов в имени не окажется.

ГИПЕРССЫЛКА для открытия файла
При помощи функции ГИПЕРССЫЛКА так же можно указать путь к файлу, который необходимо открыть по нажатии ячейки:
=ГИПЕРССЫЛКА(«C:UsersДмитрийDesktopКнига 1.xls»;»Открыть книгу Книга 1.xls»)
Путь должен быть корректным, а имя файла необходимо указывать с расширением.

Ложка дегтя
В качестве адреса для функции ГИПЕРССЫЛКА нельзя применить и открытие книги и одновременный переход на нужный лист и ячейку этой книги. Т.е. нельзя указать что-то вроде:
=ГИПЕРССЫЛКА(«C:UsersДмитрийDesktopКнига1.xls#Лист2!D4″;»Открыть книгу Книга 1.xls»)
Это связано с ограничением именно самой функции и на момент написания статьи точно не работало.

Так же см.:
Как массово изменить гиперссылки?
Как получить адрес гиперссылки из ячейки
Как сделать гиперссылку на процедуру?


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

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
 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

Добрый день! Все решения по открыванию интернет-сайта по ссылке через VBA, которые я видел, открывают его в Internet Explorer. Ни для кого не секрет, что он загибается. Как открыть ссылку браузером по умолчанию или хотя бы MS Edge? Спасибо!

 

Dima S

Пользователь

Сообщений: 2063
Регистрация: 01.01.1970

что вы подразумеваете под «открыванием интернет-сайта по ссылке через VBA»?
просто переход по ссылке через браузер или получение каких то данных в переменную?(при этом не обязательно показывать что либо пользователю)

 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

Dima S, имею в виду открыть сайт в браузере

Изменено: Rigel4421.06.2020 23:14:38

 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

#4

21.06.2020 23:16:54

Сам отвечу на свой вопрос. Нашел на просторах интернета:

https://www.devhut.net/2018/02/01/vba-open-a-url-in-firefox-chrome/

Вроде работает, но может можно как-то попроще?
Также не разобрался, как добавить сюда Яндекс.Браузер
К тому же тут нужно выбирать браузер, а как открыть именно браузером по умолчанию, если не знаешь, какой у пользователя установлен браузер?

Код
Enum BrowserName    'This Enum is part of Sub OpenURL()
    InternetExplorer = 1
    FireFox = 2
    Chrome = 3
    Opera = 4
    Edge = 5
    Brave = 6
End Enum
 
 
'---------------------------------------------------------------------------------------
' Procedure : OpenURL
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Open a URL in FireFox
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sURL      : URL to open in FifeFox
'
' Usage:
' ~~~~~~
' Call OpenURL("http://www.google.ca", InternetExplorer)
' Call OpenURL("devhut.net", Chrome)
' Call OpenURL("msdn.com", FireFox)
' Call OpenURL("google.ca", Opera)
' Call OpenURL("http://www.google.ca", Edge)
' Call OpenURL("http://www.google.ca", Brave)
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2014-11-13              Initial Release
' 2         2018-02-01              Updated Copyright under CC licensing
'                                   Error trapped FireFox not installed
' 3         2018-02-01              Complete revamp of the code to accomodate multiple
'                                   Browser
' 4         2020-04-27              Added Microsoft Edge
'                                   Added Brave
'---------------------------------------------------------------------------------------
Sub OpenURL(ByVal sURL As String, ByVal lBrowser As BrowserName)
    On Error GoTo Error_Handler
    Dim WSHShell              As Object
    Dim sFFExe                As String     'Executable path/filename
    Dim sProgName             As String     'Name of the Executable program
    Dim sExe                  As String     'Excutable exe filename
    Dim sCmdLineSwitch        As String     'Command line switch
    Dim sShellCmd             As String     'Shell Command
 
    'Determine the Path to FF executable
    Select Case lBrowser
        Case 1
            'https://msdn.microsoft.com/en-us/library/hh826025(v=vs.85).aspx
            sProgName = "Internet Explorer"
            sExe = "IEXPLORE.EXE"
            sCmdLineSwitch = " "
        Case 2
            'https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#Browser
            sProgName = "Mozilla Firefox"
            sExe = "Firefox.EXE"
            sCmdLineSwitch = " -new-tab "
        Case 3
            sProgName = "Google Chrome"
            sExe = "Chrome.exe"
            sCmdLineSwitch = " -tab "
        Case 4
            'http://www.opera.com/docs/switches/
            sProgName = "Opera"
            sExe = "opera.exe"
            sCmdLineSwitch = " "
        Case 5
            sProgName = "Microsoft Edge"
            sExe = "Chrome.exe"
            sCmdLineSwitch = " -tab "
        Case 6
            sProgName = "Brave"
            sExe = "brave.exe"
            sCmdLineSwitch = " -tab "
    End Select
 
    If lBrowser = 5 Then    'Special case for Edge!  Thank you Microsoft for not following the rules!
        sShellCmd = "cmd /c """ & "start microsoft-edge:" & sURL & """"
    Else
        Set WSHShell = CreateObject("WScript.Shell")
        sFFExe = WSHShell.RegRead("HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows" & _
                                  "CurrentVersionApp Paths" & sExe & "")
        sFFExe = Replace(sFFExe, Chr(34), "")    'Special case for Opera?!
        'Open the URL
        sShellCmd = """" & sFFExe & """" & "" & sCmdLineSwitch & """" & sURL & """"
    End If
    shell sShellCmd, vbHide
 
Error_Handler_Exit:
    On Error Resume Next
    If Not WSHShell Is Nothing Then Set WSHShell = Nothing
    Exit Sub
 
Error_Handler:
    If Err.Number = -2147024894 Then
        MsgBox sProgName & " does not appear to be installed on this compter", _
               vbInformation Or vbOKOnly, "Unable to open the requested URL"
    Else
        MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
               "Error Number: " & Err.Number & vbCrLf & _
               "Error Source: OpenURL" & vbCrLf & _
               "Error Description: " & Err.Description & _
               Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
               , vbOKOnly + vbCritical, "An Error has Occurred!"
    End If
    Resume Error_Handler_Exit
End Sub

Изменено: Rigel4421.06.2020 23:19:14

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

Через Shell не взлетает?

«Бритва Оккама» или «Принцип Калашникова»?

 

Александр Моторин

Пользователь

Сообщений: 958
Регистрация: 31.12.2012

#6

21.06.2020 23:40:13

Код
Public Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal FileName As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long


'------------------------------------------------------------------------
' Open Webpage in default browser
'------------------------------------------------------------------------
Public Sub OpenUrl(strURL)
    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", strURL)
End Sub
 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

#7

21.06.2020 23:42:54

Александр Моторин, пробовал, у меня ничего не открывается, просто ничего не происходит. Что не так делаю?

Код
Public Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal FileName As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long
 
 
'------------------------------------------------------------------------
' Open Webpage in default browser
'------------------------------------------------------------------------
Public Sub OpenUrl(strURL)
    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", strURL)
End Sub


Sub OpenUr()
    Call OpenUrl("https://yandex.ru")
End Sub
 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

Уточняю. У меня не работало, когда браузер по умолчанию ставил Яндекс.Браузер, с другими браузерами работает. Но что не так с Яндекс.Браузером? Есть ли способ программно узнать, какой браузер стоит по умолчанию?

Изменено: Rigel4422.06.2020 00:06:00

 

Игорь

Пользователь

Сообщений: 3631
Регистрация: 23.12.2012

#9

22.06.2020 01:09:46

Всё намного проще.
Одна строка кода (открывающая ссылку в браузере по умолчанию)

Код
CreateObject("WScript.Shell").Run "https://ExcelVBA.ru/"
 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

Я же про это и писал. Игорь спасибо за реализацию.

«Бритва Оккама» или «Принцип Калашникова»?

 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

Игорь, спасибо! Но еще раз повторюсь, метод работает не со всеми браузерами. При установке по умолчанию Яндекс.Браузер у меня выскакивает ошибка (прилагаю скрин). В других браузерах нормально, но все же, получается это не универсальное решение. Поэтому хочу программно узнать, какой браузер по умолчанию и если Яндекс — открывать, например, через Edge

Изменено: Rigel4422.06.2020 23:13:45

 

Игорь

Пользователь

Сообщений: 3631
Регистрация: 23.12.2012

Это не ошибка макроса
Это у вас в системе (windows) что-то криво установлено

Макрос делает то же самое, что вы сделали бы вручную, нажав в Windows в меню ПУСК пункт ВЫПОЛНИТЬ, вставив туда ссылку, и кликнув на ОК
Это стандартный функционал Windows (она понимает, что это ссылка, и её нужно отправить в браузер по умолчанию)
Если же у вас этот макрос выдаёт ошибку (а этот макрос у меня проверен более чем на 10 тысячах разных компов),
то искать проблему надо не в макросе, а откатывать windows до того состояния, когда она умела открывать ссылки.

 

Андрей VG

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

#13

23.06.2020 07:44:52

Доброе время суток

Цитата
Rigel44 написал:
Есть ли способ программно узнать, какой браузер стоит по умолчанию?

Проверил варианты

Windows RegKey — Default Browser Application Path

. В Windows 10 правильно записан Edge, в Window 7 Chrome. По найденному в ProgId идентификатору приложения в ветке HKEY_CLASSES_ROOTChromeHTMLshellopencommand вполне себе указан путь к браузеру по умолчанию. Дерзайте.

 

Андрей_26

Пользователь

Сообщений: 647
Регистрация: 30.01.2018

 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

Андрей VG, спасибо, это очень полезно! Но можно тупой вопрос, как залезть через VBA в произвольную ветвь реестра? Я умею только работать с ветвью VBA через GetSetting

Изменено: Rigel4423.06.2020 09:21:36

 

Андрей VG

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

#16

23.06.2020 10:04:46

Цитата
Rigel44 написал:
как залезть через VBA в произвольную ветвь реестра?

Почитайте

, там и другого полезного не мало.

P. S. Медведь, а вот гранат не надо — палки будет достаточно :)

 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

#17

23.06.2020 22:21:03

Андрей VG, здорово! спасибо!

Извините, снова вопросы. Почему вы написали ветку HKEY_CLASSES_ROOTChromeHTMLshellopencommand — у меня, например, Crome не установлен, поэтому и ветки такой нет. Да и почему в ветке хрома должен быть адрес браузера по умолчанию?
Смотрю ветку HKEY_CLASSES_ROOThttpshellopencommand — действительно, вижу адрес «C:Program FilesInternet ExplorerIEXPLORE.EXE» %1 , но у меня сейчас по умолчанию не IE стоит, а там адрес IE. В общем, не понимаю, уж простите ((

Что-то похожее нашел вот в этой ветке:

Код
HKEY_CURRENT_USERSoftwareMicrosoftWindowsShellAssociati­onsUrlAssociationshttpUserChoice

Значение переменной ProgId: YandexHTML.44X6GKC2M3EKCRFCQB634HVWGE

 

Андрей VG

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

#18

23.06.2020 22:48:26

Цитата
Rigel44 написал:
Что-то похожее нашел вот в этой ветке:HKEY_CURRENT_USERSoftwareMicrosoftWindowsShellAssociati­­onsUrlAssociationshttpUserChoice

Правильно ли я понимаю, что статью по ссылке вы не читали? Так как именно там указывалось посмотреть progId браузера по умолчанию в найденной вами ветке.

Забавно :)

Изменено: Андрей VG23.06.2020 23:16:25

 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

Андрей VG, да, видимо поторопился. спасибо.
Сейчас начал «играться» с командами по чтению и записи из реестра при помощи объекта WshShell, в итоге в редакторе реестра исчезла ветка VBA (HKEY_CURRENT_USERSoftwareVB and VBA Program Settings), т.е. ее не видно в дереве. При этом пишет и читает программно без проблем. То же самое при попытке записать в другие папки тоже не отображаются никакие изменения, при этом программно все нормально читает. Такое ощущение, что реестр не обновляется больше, что это может быть???

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#20

24.06.2020 17:44:11

Который день не могу понять, чем обычное

Код
ThisWorkbook.FollowHyperlink "https://www.planetaexcel.ru/"

не подходит?

 

Андрей VG

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

#21

24.06.2020 17:48:24

Цитата
RAN написал:
не подходит?

А помучаться? А записать куда-нибудь что-нибудь,. чтобы всё пропало? :)

Цитата
Rigel44 написал:
начал «играться» с командами по чтению и записи из реестра при помощи объекта WshShell

Надеюсь точку восстановления перед этим сделали? Читать читал реестр и через WshShell и через WMI, а вот запись делал только штатными VBA WriteSettings, поэтому ничего сказать и посоветовать не могу.

 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

#22

24.06.2020 20:45:04

Цитата
RAN написал:
Который день не могу понять, чем обычноеКод ? 1ThisWorkbook.FollowHyperlink » https://www.planetaexcel.ru/ «не подходит?

Вот поэтому, у меня не работает:

Прикрепленные файлы

  • Скриншот 24-06-2020 204359.png (10.92 КБ)

 

Игорь

Пользователь

Сообщений: 3631
Регистрация: 23.12.2012

Вам уже второй простой проверенный код дали, из одной строки
Дальше будете искать коды и пробовать, или перечитаете то что я вам написал, насчёт сбоя в реестре из-за кривой установки браузера?
(и у вас после решения этой проблемы все эти макросы заработают без ошибок)

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#24

24.06.2020 23:17:31

На всякий случай

Код
Sub qqq()
    x = Shell("""C:Program FilesInternet ExplorerIEXPLORE.EXE""" & """http://www.planetaexcel.ru""", vbNormalNoFocus)
    x = Shell("""C:Program FilesMozilla Firefoxfirefox.exe""" & """https://www.mail.ru""", vbNormalNoFocus)
    x = Shell("""C:Program FilesOperalauncher.exe""" & """https://www.planetaexcel.ru""", vbNormalNoFocus)
End Sub
 

Rigel44

Пользователь

Сообщений: 69
Регистрация: 20.12.2014

#25

24.06.2020 23:31:02

Игорь, я переустанавливал браузер, ошибка не ушла. Поэтому сделал ее обход: если по умолчанию Яндекс, тогда запускается Edge, в остальных случаях по умолчанию. Я не знаю, проблема ли это моего компьютера или Яндекса, задача, чтобы сайт открывался, я ее решил. Всем спасибо за помощь!

Понравилась статья? Поделить с друзьями:
  • Vba excel ссылка на активный лист
  • Vba excel ссылка на активную ячейку
  • Vba excel срезы строк
  • Vba excel среднее значение
  • Vba excel среднее арифметическое