Создание гиперссылки в 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:
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:
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:
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!
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.
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:
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:
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.
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:
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.
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.
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:
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
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.
- 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.”
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
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
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
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
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
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
Run this code using the F5 key or manually. Then, it will create a hyperlink in cell A1 in the sheet “Example 1.”
When you click on the hyperlink “Main Sheet,” it redirects to the main sheet.
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.
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
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
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
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
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
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
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
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
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
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.
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
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
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.
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
Step 2: Use the Active cell object to get open the hyperlink add method.
Code:
Private Sub hyper() ActiveCell.Hyperlinks.Add( End Sub
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.
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:
Private Sub hyper1() Worksheets("sub").Select End Sub
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
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
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:
Private Sub hyper2() Dim ws As Worksheet End Sub
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
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
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
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
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
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
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 Loops
- VBA RGB
- VBA Break for Loop
- VBA XML
Hyperlinks in Excel VBA – Explained with Examples!
We can do many things using Hyperlinks in Excel VBA. The following examples will show you how to add or create and remove hyperlinks, how to open files using hyperlinks. And sending emails using hyperlinks in Excel VBA.
Important Methods and properties of Hyperlinks Object:
Add Method:
Add method of hyperlinks will add a hyperlink to a specific range or shape.
Delete Method:
Delete method of hyperlinks will delete the hyperlink.
Count Property:
Count property of hyperlinks will returns number of hyperlinks in object hyperlinks collection.
Important Methods of Hyperlink Object:
AddToFavorites:
AddToFavorites method of workbook will add a shortcut to the workbook or hyperlink to the Favorites folder.
CreateNewDocument:
CreateNewDocument method of hyperlink will creates a new document linked to the specified hyperlink.
Follow:
Follow method of a hyperlink will displays a cached document, if it’s exist. Otherwise will resolve the hyperlink to download the target document and displays the document in the appropriate application.
Important Properties of Hyperlink Object:
Address:
Address property of hyperlink object will returns the address of the hyperlink. It can be also used for setting an address value the hyperlink of the target document.
Creator:
Creator property of hyperlink object will the application in which this object was created.
EmailSubject:
EmailSubject property of hyperlink object will returns the subject line of the email. You can also use this property to set the subject line of hyperlink email.
Name:
Name property of hyperlink object will return name of the object in text format.
Parent:
Parent property of hyperlink object will return the parent object for the specified object.
Range:
Range property of hyperlink object will returns a range where hyperlink is attached.
ScreenTip:
ScreenTip property of hyperlink object will return the ScreenTip label of a hyperlink.
Shape:
Shape property of hyperlink object will return a Shape object that represents the shape attached to the hyperlink.
SubAddress:
SubAddress property of hyperlink object will return the location of the document associated with the hyperlink.
TextToDisplay:
TextToDisplay property of hyperlink object will return label of the hyperlink. You an also use this property to set the caption to be displayed for the specified hyperlink. Address of the hyperlink. Will be the default label.
Hyperlinks Examples using Excel VBA:
Following are the examples on using Hyperlinks in Excel with VBA.
Add Create Hyperlinks in Excel VBA:
The below example code will show you adding hyperlinks using Excel VBA.
Code:
Sub sbCreatingHyperLink() ActiveSheet.Hyperlinks.Add Range("A5"), "https://www.analysistabs.com" End Sub
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert New Module
- Copy the above code and Paste in the code window
- Press F5 to execute it
- You can see a new hyperlink is added at A5
Removing Hyperlinks in Excel VBA:
The below example code will show you removing hyperlinks using Excel VBA.
Code:
Sub sbRemovingHyperLink() Range("A5").Hyperlinks.Delete End Sub
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert New Module
- Copy the above code and Paste in the code window
- Press F5 to execute it
- It should remove the hyperlink from A5
VBA Open File Folder Website Using FollowHyperlink method in Excel:
The below example code will show you opening files, folders or a specific website using FollowHyperlink in Excel VBA.
Code:
Sub sbOpenAnything() Dim sXLFile As String Dim sFolder As String Dim sWebsite As String sFolder = "C:Temp" ' You can change as per your requirement sXLFile = "C:Temptest1.xls" ' You can change as per your requirement sWebsite = "https://www.analysistabs.com/" ' You can change as per your requirement ActiveWorkbook.FollowHyperlink Address:=sFolder, NewWindow:=True 'Open Folder ActiveWorkbook.FollowHyperlink Address:=sXLFile, NewWindow:=True 'Open excel workbook ActiveWorkbook.FollowHyperlink Address:=sWebsite, NewWindow:=True 'Open Website End Sub
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert New Module
- Copy the above code and Paste in the code window
- Change the required file, folder and website to open
- Press F5 to execute it
- It should open the all file, folder and website mentioned in the code
VBA Create Send Emails Using FollowHyperlink Method – Send Keys in Excel:
The below example code will show you how to send an email using FollowHyperlink Method – Send Keys in Excel VBA.
Code:
Sub sbCreatingEmail() Dim sMsg As String Dim Recipient As String Dim RecipientCC As String Dim RecipientBCC As String Dim sSub As String Dim sHLink As String Recipient = "test@org.email.com" RecipientCC = "test@org.email.com" RecipientBCC = "test@org.email.com" sSub = "Test Mail" sMsg = "Hi, this is a auto generated mail from excel" sHLink = "mailto:" & Recipient & "?" & "cc=" & RecipientCC & "&" & "bcc=" & RecipientBCC & "&" sHLink = sHLink & "subject=" & sSub & "&" sHLink = sHLink & "body=" & sMsg ActiveWorkbook.FollowHyperlink (sHLink) Application.Wait (Now + TimeValue("0:00:03")) Application.SendKeys "%s" 'Send Keys End Sub
VBA to loop through all hyperlinks in a worksheet:
We can use hyperlinks collection of an worksheet to loop through all hyperlinks in a spread sheet. The following example will show you to display all link address of the hyper links in the worksheet.
Code:
Sub sbLoopThroughAllLinksinSheet() 'For each link in the worksheet For Each lnk In Sheets("Sheet1").Hyperlinks 'display link address MsgBox lnk.Address Next End Sub
VBA to loop through all hyperlinks in a workbook :
We can use hyperlinks collection of an worksheet to loop through all hyperlinks in a workbook. The following example will show you to display all link address of the hyper links in active workbook by sheet.
Code:
Sub sbLoopThroughAllLinksinWorkbook() 'for each sheet in active workbook For Each sh In ActiveWorkbook.Sheets 'For each link in a shet For Each lnk In sh.Hyperlinks 'display worksheet name and link address MsgBox sh.Name & ":" & lnk.Address Next Next End Sub
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Related Posts
-
- Important Methods and properties of Hyperlinks Object:
- Add Method:
- Delete Method:
- Count Property:
- Important Methods of Hyperlink Object:
- AddToFavorites:
- CreateNewDocument:
- Follow:
- Important Properties of Hyperlink Object:
- Address:
- Creator:
- EmailSubject:
- Name:
- Parent:
- Range:
- ScreenTip:
- Shape:
- SubAddress:
- TextToDisplay:
- Hyperlinks Examples using Excel VBA:
- Add Create Hyperlinks in Excel VBA:
- Removing Hyperlinks in Excel VBA:
- VBA Open File Folder Website Using FollowHyperlink method in Excel:
- VBA Create Send Emails Using FollowHyperlink Method – Send Keys in Excel:
- VBA to loop through all hyperlinks in a worksheet:
- VBA to loop through all hyperlinks in a workbook :
- Important Methods and properties of Hyperlinks Object:
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
25 Comments
-
James
March 28, 2014 at 1:03 AM — ReplyHow do I verify many links in Excel 2007?
-
PNRao
March 29, 2014 at 12:24 PM — ReplyHi James,
Please check the examples, I have added the required examples to loop through the hyperlinks in a worksheet or workbook.Thanks-PNRo!
-
Gary
May 21, 2014 at 8:42 PM — ReplyHi,
I am trying to hyperlink results from a search utility to the worksheet that the result was found. Is this possible?
Kind Regards,
Gary
-
PNRao
May 25, 2014 at 7:12 PM — ReplyHi Gary,
Yes, it’s possible. You can extract the html page with search results. Then you can loop through the each link in the html Document object.Thanks-PNRao!
-
kyle
June 5, 2014 at 4:08 PM — Replyhow do i create a button to open up different sheets with in my workbook
-
PNRao
June 7, 2014 at 6:00 PM — ReplyHi Kyle,
Please follow the below steps:
1. Place a button in worksheet: (Go to Insert menu and choose a rectangle shape from shapes group)
2. Add hyperlink: (Right Click on rectangle shape which is added in above step and click on ‘Hyperlink…’ command in right click menu)
3. Select required sheet: (Click on the ‘Place in this document’ and select required sheet to link), then Press OK button.Hope this help! Thanks-PNRao!
-
Jonny
July 17, 2014 at 3:12 PM — ReplyHi PNRao,
I’m trying to write a code (which i think uses several of these commands) which will open several hyperlinks, which are to online PDFs, and print them. Ideally I would have this on a button for different combinations of links.Additionally some of these links, i would only want to print some pages…
Is this possible?
Thanks. -
PNRao
July 17, 2014 at 7:38 PM — ReplyHi Jonny,
You can use FollowHyperlink method to open any file.
To print the PDF file, you can use ShellExecute command as shown below:
‘[Code]—–Copy this code and place in a new module
Public Declare Function ShellExecute Lib “shell32.dll” Alias “ShellExecuteA” ( _
ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As LongSub sbPrintPDFs()
Dim tempPrint
Dim strFile As StringstrFile = “C:Test.pdf” ‘ Your PDF File Path
‘To pen a PDF
‘tempPrint = fnOpenPDF(0, strFile)‘To Print PDF
tempPrint = fnPrintPDF(0, strFile)
End SubPublic Function fnPrintPDF(lngHw As Long, strFileName As String)
On Error Resume Next
Dim X As Long
X = ShellExecute(lngHw, “Print”, strFileName, 0&, 0&, 3)
End FunctionPublic Function fnOpenPDF(lngHw As Long, strFileName As String)
On Error Resume Next
Dim X As Long
X = ShellExecute(lngHw, “Open”, strFileName, 0&, 0&, 3)
End Function‘[/Code]
And I am not sure about printing only specific pages!
Hope this helps! Thanks-PNRao!
-
Jonny
July 18, 2014 at 12:25 PM — ReplyThanks,
This comes up with a compile error “expected: string constant”and where you have “strFile = “C:Test.pdf” ‘ Your PDF File Path” – Is this assuming my file will already be saved to my hard drive? The files are online and need to stay there in case of changes.
Any suggestions appreciated!
-
PNRao
July 18, 2014 at 6:55 PM — ReplystrFile = “C:Test.pdf” is your file name. i.e; you need to replace “C:Test.pdf” with your file name (something like “www.website/filename.pdf”)
Thanks-PNRao!
-
Gavrav
July 24, 2014 at 12:57 PM — ReplyHi,
I am trying to execute query statement in ssms 2005 by automatically clicking that query statement as hyperlink which is in excel. Is it possible to interlink that query statement which is actually written in excel with help of macro or something related to that. -
Peter
January 10, 2015 at 2:25 AM — ReplyHi-
Thanks for this great resource!
I have two columns of data: one is a list of article headlines and second is a list of URLs to the articles (headlines and associated URLs are in the same row). I’m trying to merge the two columns to create hyperlinked headlines that link to the appropriate article. This is a function that can be done using the CTRL-K Insert Hyperlink function on a one at a time basis but I’m looking to be able to accomplish this one a larger scale. Any thoughts?
thanks!
-Peter -
Dana
April 17, 2015 at 11:26 PM — ReplyHello dear author.
Please help me to understand Visual basic. I have a command button in excel, which opens my Word file. After i make changes in this Word document i do Save As and change file saving directory. Please, tell me how i can add Hyperlink to the excel automatically AFTER that Word file have been saved to the new directory?
Thanks a lot. -
Kirk
May 18, 2015 at 10:16 PM — ReplyHi PNRao,
I tried the code with my master sheet, but it did generate the hyperlinks. I am trying to set up a workbook where future parts can be added (each part will be a new sheet). As I have it now, when the sheet is made and some old data is entered, it takes the name from that data (specifically from J2) to label the sheet. The master sheet already generates the names of the sheets, but I cant get them to hyperlink to each of the respective sheets. Any help on this would be appreciated, thanks.
-Kirk -
Dave
June 2, 2015 at 3:00 AM — ReplyHello,
I have a spreadsheet with links to documents that have to be opened/copied to another location. Also while opening the file it would need to search the sheet for a keyword or two. Then save the pdf / document to a different location. Is this possible with vba? -
phil
July 16, 2015 at 6:40 PM — ReplyThanks for your thorough examples.
I want to hide hyperlinks when I print the worksheet.
My approach is/was to collect all the hyperlinks
of the worksheet in an array, then set the name in each
hyperlink to spaces. After printing I will go back and
restore the hyperlink names from the array.Here is my testing code:
ReDim hArray(1 To ActiveSheet.Hyperlinks.Count) As Variant
Debug.Print “=.=.=.=.=.=.=.=.=.=.=.=.=.=.=”
Debug.Print “active worksheet ” & ActiveSheet.Name
n = 1 ‘hArray is base 1
Set WorkRng = ActiveSheet.UsedRange ‘range to search = the entire worksheet
For Each Rng In WorkRng ‘search for hyperlink cells
If Rng.Hyperlinks.Count > 0 Then ‘this cell refers to a hyperlink
hArray(n) = Rng.Hyperlinks(1).Name
Debug.Print n & “___________________________”
Debug.Print “name in array ” & hArray(n)
Debug.Print “name before ” & Rng.Hyperlinks(1).Name
Debug.Print “text before ” & Rng.Hyperlinks(1).TextToDisplayRng.Hyperlinks(1).TextToDisplay = ”
Debug.Print “text after ” & Rng.Hyperlinks(1).TextToDisplay
‘Rng.Hyperlinks(1).Name = ”
‘Debug.Print “name after ” & Rng.Hyperlinks(1).Name
n = n + 1
End If
NextDebug output:
=.=.=.=.=.=.=.=.=.=.=.=.=.=.=
active worksheet Sheet1
1___________________________
name in array Auto(1)
name before Auto(1)
text before Auto(1)
text after Auto(1)
2___________________________
name in array Auto(2)
name before Auto(2)
text before Auto(2)
text after Auto(2)
3___________________________
name in array Condo Declarations
name before Condo Declarations
text before Condo Declarations
text after Condo Declarations
4___________________________
name in array Payment
name before Payment
text before Payment
text after Payment
5___________________________
name in array Invoice
name before Invoice
text before Invoice
text after Invoice
================================1. Notice that Rng.Hyperlinks(1).Name = ” is commented out. When
I un-comment that I get “wrong number of arguments or invalid property assignment”
2. Although Rng.Hyperlinks(1).TextToDisplay = ” does not abort, the
hyperlink label is not actually cleared.. -
PNRao
July 16, 2015 at 10:42 PM — Reply -
Allen
September 21, 2015 at 3:11 PM — ReplyHi PNRao. For example I have a spreadsheet with 2 columns – one is the display text in column A and the URL address in column B. How do I create a macro so that it will recursively update all my cells in column A with the URL address that’s found in column B?
Thanks.
Allen
-
Zahar
October 16, 2015 at 9:55 AM — ReplyHi PNRao.I need to print PDF from hyperlink from specific cell (e.g cell A2). is it possible?. your code will retrieve PDF from outside excel (e.g hard disk or web)
-
Partha
December 29, 2015 at 11:17 AM — ReplyDear Mr. Rao
Is it possible to create a hyperlink with username & password to open a password protected site in a single click from excel?
Regards
Partha
-
Giorgio Tassi
December 30, 2015 at 5:05 PM — ReplyGood morning, I have tried to sendi an e-mai of a worksheet following your instructions. I got to the stage where the e-mail is ready, with the correct addresses and subject text and attaching text. However no enclosure attached and a message advising that “Application.SendKeys “%s” ‘Send Keys’ is not running in a Macintosh platform. Can you pls advise the correction to adjust the instruction for a Mac with OS X El Capitan version 10.11.1 using Excel 2011 for Mac . Many thanks and best regards from Italy.
ActiveWorkbook.FollowHyperlink (sHLink)
Application.Wait (Now + TimeValue(“0:00:03”))
Application.SendKeys “%s” ‘Send Keys -
Ramaiah Ganta
March 24, 2016 at 1:04 AM — ReplyHow we can give the hyperlink for respective folder’s files name in active workbook
-
mary
October 6, 2016 at 11:31 PM — ReplyHow do I write the code in visual basic for excel to automatically check my hyperlinks to make sure they are good upon opening my excel sheet. And if the links are broken how to find the file . Some times my file names get changed like by date or revisions
-
Amol
October 17, 2016 at 10:25 PM — ReplyI have multiple sheets in my excel and I want to add hyperlink to each sheet and hide it. How can I do it with VBA?
-
Arun
March 14, 2018 at 7:22 PM — ReplyHow we open a hyperlinks in VBA. step by step
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
The first sheet of my workbook is like a contents page. Each cell in column A holds an IP address string. For each IP address string, there is a worksheet named with the IP address.
I want to turn the string in the cells in column A into hyperlinks to their corresponding sheets (cell A1 of the destination sheet).
I only need the VBA line that makes the hyperlink; I can figure out the looping, etc. Remember that the name of the sheet to be linked to is the same as the value of the cell that will become the link.
Research has only brought up forum posts that give a stack of code without explaining any of it.
asked Mar 21, 2012 at 21:57
4
I recorded a macro making a hiperlink. This resulted.
ActiveCell.FormulaR1C1 = "=HYPERLINK(""[Workbook.xlsx]Sheet1!A1"",""CLICK HERE"")"
answered Mar 21, 2012 at 22:10
curialcurial
5144 silver badges17 bronze badges
This is the code I use for creating an index sheet.
Sub CreateIndexSheet()
Dim wSheet As Worksheet
ActiveWorkbook.Sheets.Add(Before:=Worksheets(1)).Name = "Contents" 'Call whatever you like
Range("A1").Select
Application.ScreenUpdating = False 'Prevents seeing all the flashing as it updates the sheet
For Each wSheet In Worksheets
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & wSheet.Name & "'" & "!A1", TextToDisplay:=wSheet.Name
ActiveCell.Offset(1, 0).Select 'Moves down a row
Next
Range("A1").EntireColumn.AutoFit
Range("A1").EntireRow.Delete 'Remove content sheet from content list
Application.ScreenUpdating = True
End Sub
bad_coder
10.8k20 gold badges44 silver badges68 bronze badges
answered Jul 6, 2015 at 13:26
LeeLee
1811 silver badge2 bronze badges
1
Something like the following will loop through column A in the Control sheet and turn the values in the cells into Hyperlinks. Not something I’ve had to do before so please excuse bugs:
Sub CreateHyperlinks()
Dim mySheet As String
Dim myRange As Excel.Range
Dim cell As Excel.Range
Set myRange = Excel.ThisWorkbook.Sheets("Control").Range("A1:A5") '<<adjust range to suit
For Each cell In myRange
Excel.ThisWorkbook.Sheets("Control").Hyperlinks.Add Anchor:=cell, Address:="", SubAddress:=cell.Value & "!A1" '<<from recorded macro
Next cell
End Sub
answered Mar 21, 2012 at 22:16
whytheqwhytheq
34k64 gold badges170 silver badges265 bronze badges
1
The «!» sign is the key element. If you have a cell object (like «mycell» in following code sample) and link a cell to this object you must pay attention to ! element.
You must do something like this:
.Cells(i, 2).Hyperlinks.Add Anchor:=.Range(Cells(i, 2).Address), Address:="", _
SubAddress:= "'" & ws.Name & "'" & _
"!" & mycell.Address
c0der
18.3k6 gold badges32 silver badges65 bronze badges
answered Mar 15, 2014 at 15:58
If you need to hyperlink Sheet1 to all or corresponding sheets, then use simple vba code. If you wish to create a radio button, then assign this macro to that button ex «Home Page».
Here is it:
Sub HomePage()
'
' HomePage Macro
'
' This is common code to go to sheet 1 if do not change name for Sheet1
'Sheets("Sheet1").Select
' OR
' You can write you sheet name here in case if its name changes
Sheets("Monthly Reports Home").Select
Range("A1").Select
End Sub
answered Aug 17, 2016 at 12:13
This macro adds a hyperlink to the worksheet with the same name, I also modify the range to be more flexible, just change the first cell in the code. Works like a charm
Sub hyper()
Dim cl As Range
Dim nS As String
Set MyRange = Sheets("Sheet1").Range("B16")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each cl In MyRange
nS = cl.Value
cl.Hyperlinks.Add Anchor:=cl, Address:="", SubAddress:="'" & nS & "'" & "!B16", TextToDisplay:=nS
Next
End Sub
answered Jul 18, 2017 at 4:00
In my implementation, the cell I was referencing could have been several options. I used the following format where ‘ws’ is the current worksheet being edited
For each ws in Activeworkbook.Worksheets
For i…
For j...
...
ws.Cells(i, j).Value = "=HYPERLINK(""#'" & SHEET-REF-VAR & "'!" & CELL-REF-VAR & """,""" & SHEET-REF-VAR & """)"
answered Jan 2, 2020 at 22:38
0
Excel allows having hyperlinks in cells which you can use to directly go to that URL.
For example, below is a list where I have company names which are hyperlinked to the company website’s URL. When you click on the cell, it will automatically open your default browser (Chrome in my case) and go to that URL.
There are many things you can do with hyperlinks in Excel (such as a link to an external website, link to another sheet/workbook, link to a folder, link to an email, etc.).
In this article, I will cover all you need to know to work with hyperlinks in Excel (including some useful tips and examples).
How to Insert Hyperlinks in Excel
There are many different ways to create hyperlinks in Excel:
- Manually type the URL (or copy paste)
- Using the HYPERLINK function
- Using the Insert Hyperlink dialog box
Let’s learn about each of these methods.
Manually Type the URL
When you manually enter a URL in a cell in Excel, or copy and paste it in the cell, Excel automatically converts it into a hyperlink.
Below are the steps that will change a simple URL into a hyperlink:
- Select a cell in which you want to get the hyperlink
- Press F2 to get into the edit mode (or double click on the cell).
- Type the URL and press enter. For example, if I type the URL – https://trumpexcel.com in a cell and hit enter, it will create a hyperlink to it.
Note that you need to add http or https for those URLs where there is no www in it. In case there is www as the prefix, it would create the hyperlink even if you don’t add the http/https.
Similarly, when you copy a URL from the web (or some other document/file) and paste it in a cell in Excel, it will automatically be hyperlinked.
Insert Using the Dialog Box
If you want the text in the cell to be something else other than the URL and want it to link to a specific URL, you can use the insert hyperlink option in Excel.
Below are the steps to enter the hyperlink in a cell using the Insert Hyperlink dialog box:
- Select the cell in which you want the hyperlink
- Enter the text that you want to be hyperlinked. In this case, I am using the text ‘Sumit’s Blog’
- Click the Insert tab.
- Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
- In the Insert Hyperlink dialog box, enter the URL in the Address field.
- Press the OK button.
This will insert the hyperlink the cell while the text remains the same.
There are many more things you can do with the ‘Insert Hyperlink’ dialog box (such as create a hyperlink to another worksheet in the same workbook, create a link to a document/folder, create a link to an email address, etc.). These are all covered later in this tutorial.
Insert Using the HYPERLINK Function
Another way to insert a link in Excel can be by using the HYPERLINK Function.
Below is the syntax:
HYPERLINK(link_location, [friendly_name])
- link_location: This can be the URL of a web-page, a path to a folder or a file in the hard disk, place in a document (such as a specific cell or named range in an Excel worksheet or workbook).
- [friendly_name]: This is an optional argument. This is the text that you want in the cell that has the hyperlink. In case you omit this argument, it will use the link_location text string as the friendly name.
Below is an example where I have the name of companies in one column and their website URL in another column.
Below is the HYPERLINK function to get the result where the text is the company name and it links to the company website.
In the examples so far, we have seen how to create hyperlinks to websites.
But you can also create hyperlinks to worksheets in the same workbook, other workbooks, and files and folders on your hard disk.
Let’s see how it can be done.
Create a Hyperlink to a Worksheet in the Same Workbook
Below are the steps to create a hyperlink to Sheet2 in the same workbook:
- Select the cell in which you want the link
- Enter the text that you want to be hyperlinked. In this example, I have used the text ‘Link to Sheet2’.
- Click the Insert tab.
- Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
- In the Insert Hyperlink dialog box, select ‘Place in This Document’ option in the left pane.
- Enter the cell which you want to hyperlink (I am going with the default A1).
- Select the sheet that you want to hyperlink (Sheet2 in this case)
- Click OK.
Note: You can also use the same method to create a hyperlink to any cell in the same workbook. For example, if you want to link to a far off cell (say K100), you can do that by using this cell reference in step 6 and selecting the existing sheet in step 7.
You can also use the same method to link to a defined name (named cell or named range). If you have any named ranges (named cells) in the workbook, these would be listed in under the ‘Defined Names’ category in the ‘Insert Hyperlink’ dialog box.
Apart from the dialog box, there is also a function in Excel that allows you to create hyperlinks.
So instead of using the dialog box, you can instead use the HYPERLINK formula to create a link to a cell in another worksheet.
The below formula will do this:
=HYPERLINK("#"&"Sheet2!A1","Link to Sheet2")
Below is how this formula works:
- “#” would tell the formula to refer to the same workbook.
- “Sheet2!A1” tells the formula the cell that should be linked to in the same workbook
- “Link to Sheet2” is the text that appears in the cell.
Create a Hyperlink to a File (in the same or different folders)
You can also use the same method to create hyperlinks to other Excel (and non-Excel) files that are in the same folder or are in other folders.
For example, if you want to open a file with the Test.xlsx which is in the same folder as your current file, you can use the below steps:
- Select the cell in which you want the hyperlink
- Click the Insert tab.
- Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
- In the Insert Hyperlink dialog box, select ‘Existing File or Webpage’ option in the left pane.
- Select ‘Current folder’ in the Look in options
- Select the file for which you want to create the hyperlink. Note that you can link to any file type (Excel as well as non-Excel files)
- [Optional] Change the Text to Display name if you want to.
- Click OK.
In case you want to link to a file which is not in the same folder, you can Browse the file and then select it. To Browse the file, click on the folder icon in the Insert Hyperlink dialog box (as shown below).
You can also do this using the HYPERLINK function.
The below formula will create a hyperlink that links to a file in the same folder as the current file:
=HYPERLINK("Test.xlsx","Test File")
In case the file is not in the same folder, you can copy the address of the file and use it as the link_location.
Create a Hyperlink to a Folder
This one also follows the same methodology.
Below are the steps to create a hyperlink to a folder:
- Copy the folder address for which you want to create the hyperlink
- Select the cell in which you want the hyperlink
- Click the Insert tab.
- Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
- In the Insert Hyperlink dialog box, paste folder address
- Click OK.
You can also use the HYPERLINK function to create a hyperlink that points to a folder.
For example, the below formula will create a hyperlink to a folder named TEST on the desktop and as soon as you click on the cell with this formula, it will open this folder.
=HYPERLINK("C:UserssumitDesktopTest","Test Folder")
To use this formula, you will have to change the address of the folder to the one you want to link to.
Create Hyperlink to an Email Address
You can also have hyperlinks which open your default email client (such as Outlook) and have the recipients email and the subject line already filled in the send field.
Below are the steps to create an email hyperlink:
- Select the cell in which you want the hyperlink
- Click the Insert tab.
- Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
- In the insert dialog box, click on ‘E-mail Address’ in the ‘Link to’ options
- Enter the E-mail address and the Subject line
- [Optional] Enter the text you want to be displayed in the cell.
- Click OK.
Now when you click on the cell which has the hyperlink, it will open your default email client with the email and subject line pre-filled.
You can also do this using the HYPERLINK function.
The below formula will open the default email client and have one email address already pre-filled.
=HYPERLINK("mailto:abc@trumpexcel.com","Send Email")
Note that you need to use mailto: before the email address in the formula. This tells the HYPERLINK function to open the default email client and use the email address that follows.
In case you want to have the subject line as well, you can use the below formula:
=HYPERLINK("mailto:abc@trumpexcel.com,?cc=&bcc=&subject=Excel is Awesome","Generate Email")
In the above formula, I have kept the cc and bcc fields as empty, but you can also these emails if needed.
Here is a detailed guide on how to send emails using the HYPERLINK function.
Remove Hyperlinks
If you only have a few hyperlinks, you can remove these manually, but if you have a lot, you can use a VBA Macro to do this.
Manually Remove Hyperlinks
Below are the steps to remove hyperlinks manually:
- Select the data from which you want to remove hyperlinks.
- Right-click on any of the selected cell.
- Click on the ‘Remove Hyperlink’ option.
The above steps would instantly remove hyperlinks from the selected cells.
In case you want to remove hyperlinks from the entire worksheet, select all the cells and then follow the above steps.
Remove Hyperlinks Using VBA
Below is the VBA code that will remove the hyperlinks from the selected cells:
Sub RemoveAllHyperlinks() 'Code by Sumit Bansal @ trumpexcel.com Selection.Hyperlinks.Delete End Sub
If you want to remove all the hyperlinks in the worksheet, you can use the below code:
Sub RemoveAllHyperlinks() 'Code by Sumit Bansal @ trumpexcel.com ActiveSheet.Hyperlinks.Delete End Sub
Note that this code will not remove the hyperlinks created using the HYPERLINK function.
You need to add this VBA code in the regular module in the VB Editor.
If you need to remove hyperlinks quite often, you can use the above VBA codes, save it in the Personal Macro Workbook, and add it to your Quick Access Toolbar. This will allow you to remove hyperlinks with a single click and it will be available in all the workbooks on your system.
Here is a detailed guide on how to remove hyperlinks in Excel.
Prevent Excel from Creating Hyperlinks Automatically
For some people, it’s a great feature that Excel automatically converts a URL text to a hyperlink when entered in a cell.
And for some people, it’s an irritation.
If you’re in the latter category, let me show you a way to prevent Excel from automatically creating URLs into hyperlinks.
The reason this happens as there is a setting in Excel that automatically converts ‘Internet and network paths’ into hyperlinks.
Here are the steps to disable this setting in Excel:
- Click the File tab.
- Click on Options.
- In the Excel Options dialog box, click on ‘Proofing’ in the left pane.
- Click on the AutoCorrect Options button.
- In the AutoCorrect dialog box, select the ‘AutoFormat As You Type’ tab.
- Uncheck the option – ‘Internet and network paths with hyperlinks’
- Click OK.
- Close the Excel Options dialog box.
If you’ve completed the following steps, Excel would not automatically turn URLs, email address, and network paths into hyperlinks.
Note that this change is applied to the entire Excel application, and would be applied to all the workbooks that you work with.
Extract Hyperlink URLs (using VBA)
There is no function in Excel that can extract the hyperlink address from a cell.
However, this can be done using the power of VBA.
For example, suppose you have a dataset (as shown below) and you want to extract the hyperlink URL in the adjacent cell.
Let me show you two techniques to extract the hyperlinks from the text in Excel.
Extract Hyperlink in the Adjacent Column
If you want to extract all the hyperlink URLs in one go in an adjacent column, you can so that using the below code:
Sub ExtractHyperLinks() Dim HypLnk As Hyperlink For Each HypLnk In Selection.Hyperlinks HypLnk.Range.Offset(0, 1).Value = HypLnk.Address Next HypLnk End Sub
The above code goes through all the cells in the selection (using the FOR NEXT loop) and extracts the URLs in the adjacent cell.
In case you want to get the hyperlinks in the entire worksheet, you can use the below code:
Sub ExtractHyperLinks() On Error Resume Next Dim HypLnk As Hyperlink For Each HypLnk In ActiveSheet.Hyperlinks HypLnk.Range.Offset(0, 1).Value = HypLnk.Address Next HypLnk End Sub
Note that the above codes wouldn’t work for hyperlinks created using the HYPERLINK function.
Extract Hyperlink Using a Formula (created with VBA)
The above code works well when you want to get the hyperlinks from a dataset in one go.
But if you have a list of hyperlinks that keeps expanding, you can create a User Defined Function/formula in VBA.
This will allow you to quickly use the cell as the input argument and it will return the hyperlink address in that cell.
Below is the code that will create a UDF for getting the hyperlinks:
Function GetHLink(rng As Range) As String If rng(1).Hyperlinks.Count <> 1 Then GetHLink = "" Else GetHLink = rng.Hyperlinks(1).Address End If End Function
Note that this wouldn’t work with Hyperlinks created using the HYPERLINK function.
Also, in case you select a range of cells (instead of a single cell), this formula will return the hyperlink in the first cell only.
Find Hyperlinks with Specific Text
If you’re working with a huge dataset that has a lot of hyperlinks in it, it could be a challenge when you want to find the ones that have a specific text in it.
For example, suppose I have a dataset as shown below and I want to find all the cells with hyperlinks that have the text 2019 in it and change it to 2020.
And no.. doing this manually is not an option.
You can do that using a wonderful feature in Excel – Find and Replace.
With this, you can quickly find and select all the cells that have a hyperlink and then change the text 2019 with 2020.
Below are the steps to select all the cells with a hyperlink and the text 2019:
- Select the range in which you want to find the cells with hyperlinks with 2019. In case you want to find in the entire worksheet, select the entire worksheet (click on the small triangle at the top left).
- Click the Home tab.
- In the Editing group, click on Find and Select
- In the drop-down, click on Replace. This will open the Find and Replace dialog box.
- In the Find and Replace dialog box, click on the Options button.This will show more options in the dialog box.
- In the ‘Find What’ options, click on the little downward pointing arrow in the Format button (as shown below).
- Click on the ‘Choose Format From Cell’. This will turn your cursor into a plus icon with a format picker icon.
- Select any cell which has a hyperlink in it. You will notice that the Format gets visible in the box on the left of the Format button. This indicates that the format of the cell you selected has been picked up.
- Enter 2019 in the ‘Find What’ field and 2020 in the ‘Replace with’ field.
- Click on the Replace All button.
In the above data, it will change the text of four cells that have the text 2019 in it and also has a hyperlink.
You can also use this technique to find all the cells with hyperlinks and get a list of it. To do this, instead of clicking on Replace All, click on the Find All button. This will instantly give you a list of all the cell address that has hyperlinks (or hyperlinks with specific text depending on what you’ve searched for).
Note: This technique works as Excel is able to identify the formatting of the cell that you select and use that as a criterion to find cells. So if you’re finding hyperlinks, make sure you select a cell that has the same kind of formatting. If you select a cell that has a background color or any text formatting, it may not find all the correct cells.
Selecting a Cell that has a Hyperlink in Excel
While Hyperlinks are useful, there are a few things about it that irritate me.
For example, if you want to select a cell that has a hyperlink in it, Excel would automatically open your default web browser and try to open this URL.
Another irritating thing about it is that sometimes when you have a cell that has a hyperlink in it, it makes the entire cell clickable. So even if you’re clicking on the hyperlinked text directly, it still opens the browser and the URL of the text.
So let me quickly show you how to get rid of these minor irritants.
Select the Cell (without opening the URL)
This is a simple trick.
When you hover the cursor over a cell that has a hyperlink in it, you’ll notice the hand icon (which indicates if you click on it, Excel will open the URL in a browser)
Click the cell anyway and hold the left button of the mouse.
After a second, you’ll notice that the hand cursor icon changes into the plus icon, and now when you leave it, Excel will not open the URL.
Instead, it would select the cell.
Now, you can make any changes in the cell you want.
Neat trick… right?
Select a Cell by clicking on the blank space in the cell
This is another thing that might drive you nuts.
When there is a cell with the hyperlink in it as well as some blank space, and you click on the blank space, it still opens the hyperlink.
Here is a quick fix.
This happens when these cells have the wrap text enabled.
If you disable wrap text for these cells, you will be able to click on the white space on the right of the hyperlink without opening this link.
Some Practical Example of Using Hyperlink
There are useful things you can do when working with hyperlinks in Excel.
In this section, I am going to cover some examples that you may find useful and can use in your day-to-day work.
Example 1 – Create an Index of All Sheets in the Workbook
If you have a workbook with a lot of sheets, you can use a VBA code to quickly create a list of the worksheets and hyperlink these to the sheets.
This could be useful when you have 12-month data in 12 different worksheets and want to create one index sheet that links to all these monthly data worksheets.
Below is the code that will do this:
Sub CreateSummary() 'Created by Sumit Bansal of trumpexcel.com 'This code can be used to create summary worksheet with hyperlinks Dim x As Worksheet Dim Counter As Integer Counter = 0 For Each x In Worksheets Counter = Counter + 1 If Counter = 1 Then GoTo Donothing With ActiveCell .Value = x.Name .Hyperlinks.Add ActiveCell, "", x.Name & "!A1", TextToDisplay:=x.Name, ScreenTip:="Click here to go to the Worksheet" With Worksheets(Counter) .Range("A1").Value = "Back to " & ActiveSheet.Name .Hyperlinks.Add Sheets(x.Name).Range("A1"), "", _ "'" & ActiveSheet.Name & "'" & "!" & ActiveCell.Address, _ ScreenTip:="Return to " & ActiveSheet.Name End With End With ActiveCell.Offset(1, 0).Select Donothing: Next x End Sub
You can place this code in the regular module in the workbook (in VB Editor)
This code also adds a link to the summary sheet in cell A1 of all the worksheets. In case you don’t want that, you can remove that part from the code.
You can read more about this example here.
Note: This code works when you have the sheet (in which you want the summary of all the worksheets with links) at the beginning. In case it’s not at the beginning, this may not give the right results).
Example 2 – Create Dynamic Hyperlinks
In most cases, when you click on a hyperlink in a cell in Excel, it will take you to a URL or to a cell, file or folder. Normally, these are static URLs which means that a hyperlink will take you to a specific predefined URL/location only.
But you can also use a little bit for Excel formula trickery to create dynamic hyperlinks.
By dynamic hyperlinks, I mean links that are dependent on a user selection and change accordingly.
For example, in the below example, I want the hyperlink in cell E2 to point to the company website based on the drop-down list selected by the user (in cell D2).
This can be done using the below formula in cell E2:
=HYPERLINK(VLOOKUP(D2,$A$2:$B$6,2,0), "Click here")
The above formula uses the VLOOKUP function to fetch the URL from the table on the left. The HYPERLINK function then uses this URL to create a hyperlink in the cell with the text – ‘Click here’.
When you change the selection using the drop-down list, the VLOOKUP result will change and would accordingly link to the selected company’s website.
This could be a useful technique when you’re creating a dashboard in Excel. You can make the hyperlinks dynamic depending on the user selection (which could be a drop-down list or a checkbox or a radio button).
Here is a more detailed article of using Dynamic Hyperlinks in Excel.
Example 3 – Quickly Generate Simple Emails Using Hyperlink Function
As I mentioned in this article earlier, you can use the HYPERLINK function to quickly create simple emails (with pre-filled recipient’s emails and the subject line).
Single Recipient Email Id
=HYPERLINK("mailto:abc@trumpexcel.com","Generate Email")
This would open your default email client with the email id abc@trumpexcel.com in the ‘To’ field.
Multiple Recipients Email Id
=HYPERLINK("mailto:abc@trumpexcel.com,def@trumpexcel.com","Generate Email")
For sending the email to multiple recipients, use a comma to separate email ids. This would open the default email client with all the email ids in the ‘To’ field.
Add Recipients in CC and BCC List
=HYPERLINK("mailto:abc@trumpexcel.com,def@trumpexcel.com?cc=123@trumpexcel.com&bcc=456@trumpexcel.com","Generate Email")
To add recipients to CC and BCC list, use question mark ‘?’ when ‘mailto’ argument ends, and join CC and BCC with ‘&’. When you click on the link in excel, it would have the first 2 ids in ‘To’ field, 123@trumpexcel.com in ‘CC’ field and 456@trumpexcel.com in the ‘BCC’ field.
Add Subject Line
=HYPERLINK("mailto:abc@trumpexcel.com,def@trumpexcel.com?cc=123@trumpexcel.com&bcc=456@trumpexcel.com&subject=Excel is Awesome","Generate Email")
You can add a subject line by using the &Subject code. In this case, this would add ‘Excel is Awesome’ in the ‘Subject’ field.
Add Single Line Message in Body
=HYPERLINK("mailto:abc@trumpexcel.com,def@trumpexcel.com?cc=123@trumpexcel.com&bcc=456@trumpexcel.com&subject=Excel is Awesome&body=I love Excel","Email Trump Excel")
This would add a single line ‘I love Excel’ to the email message body.
Add Multiple Lines Message in Body
=HYPERLINK("mailto:abc@trumpexcel.com,def@trumpexcel.com?cc=123@trumpexcel.com&bcc=456@trumpexcel.com&subject=Excel is Awesome&body=I love Excel.%0AExcel is Awesome","Generate Email")
To add multiple lines in the body you need to separate each line with %0A. If you wish to introduce two line breaks, add %0A twice, and so on.
Here is a detailed article on how to send emails from Excel.
Hope you found this article useful.
Let me know your thoughts in the comments section.
You May Also Like the Following Excel Tutorials:
- Excel AutoCorrect
- How to Find External Links and References in Excel
- 100+ Excel Interview Questions & Answers
- Excel Text to Columns
- Excel Sparklines