Создание гиперссылки в 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
.
tresser Пользователь Сообщений: 18 |
Здравствуйте! мне необходимо макросом сформировать ссылку на файл, а затем разместить ее в форме userform, таким образом, чтобы при открытии формы ссылка на файл отображалась в форме и работала (щелчок мыши по ссылке — открытие файла). буду пизнателен |
vikttur Пользователь Сообщений: 47199 |
В чем состоит помощь? Создать пример, в котором показать все то, что Вы описали? |
tresser Пользователь Сообщений: 18 |
прошу прощения. лень треклятая))) Исполняемый макрос — Макрос 2 1. надо, чтобы в активном режиме (userform1.show) в текстбоксе (или иным способом) отображалась ссылка на выбранный файл, чтобы потом даблкликом открыть файл по указанной ссылке. можно было бы обойтись и привинченнной рядом кнопкой, но это не то. прикладываю два файла: Изменено: tresser — 21.04.2015 12:49:35 |
Hugo Пользователь Сообщений: 23251 |
Ну вообще-то совместный доступ не мешает работать макросам. И в этом файле работает… Изменено: Hugo — 21.04.2015 11:41:41 |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
Делаете обычный Label. На событие Click прописываете открытие нужного файла. Форматируете текст для этого Label под вид гиперссылки(синий шрифт, нижнее подчеркивание). Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
#6 21.04.2015 11:42:50
Работе макросов нет, а вот добавлению гиперссылок — да. При общем доступе можно использовать уже существующие гиперссылки, но нельзя их изменять и создавать новые. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
tresser Пользователь Сообщений: 18 |
|
Hugo Пользователь Сообщений: 23251 |
Дмитрий, а у меня отработало. Ничего в файле не менял — выполнил макрос, выбрал файл, он открылся и создалась ссылка, по которой тоже можно открыть тот файл. |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
Игорь, файл точно в общем доступе? Т.е. книге назначен общий доступ? Именно создание гиперссылки(через правую кнопку мыши)? Не функция ГИПЕРССЫЛКА(HYPERLINK)? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Hugo Пользователь Сообщений: 23251 |
#10 21.04.2015 17:05:24 В общем, т.к. код для редактирования недоступен P.S. На 2010 не заработало, выпадает в ошибку. Изменено: Hugo — 21.04.2015 19:26:58 |
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:
Voronika 0 / 0 / 0 Регистрация: 19.09.2013 Сообщений: 18 |
||||
1 |
||||
Excel Вставка гиперссылки через форму11.06.2019, 22:04. Показов 6126. Ответов 7 Метки vba, гиперссылка, форма (Все метки)
Здравствуйте. Помогите разобраться, пожалуйста.
Гиперссылка вставляется, выглядит всё, как должно, но ссылка не работает. Если навести на нее, отображается ссылка на файл file:///{путь к самому экселевскому файлу}/File_Pasport и пишет соответственно «Невозможно открыть файл».
0 |
140 / 123 / 50 Регистрация: 10.11.2011 Сообщений: 620 |
|
11.06.2019, 22:19 |
2 |
Что бы правильно перенести значение , нужно прикрепить файл пример для наглядности
0 |
0 / 0 / 0 Регистрация: 19.09.2013 Сообщений: 18 |
|
11.06.2019, 22:23 [ТС] |
3 |
Прикрепляю
0 |
140 / 123 / 50 Регистрация: 10.11.2011 Сообщений: 620 |
|
12.06.2019, 06:23 |
4 |
а где ваш макрос?
0 |
pashulka 4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
||||
12.06.2019, 06:40 |
5 |
|||
1 |
Voronika 0 / 0 / 0 Регистрация: 19.09.2013 Сообщений: 18 |
||||
12.06.2019, 14:02 [ТС] |
6 |
|||
pashulka, спасибо, это то, что нужно. Немного подкорректировала под остальные нужды, получилось вот так:
(Прошу прощения у модераторов, не могу найти, где кнопки для правильного оформления куска кода в сообщении…)
0 |
pashulka 4131 / 2235 / 940 Регистрация: 01.12.2010 Сообщений: 4,624 |
||||
12.06.2019, 16:13 |
7 |
|||
Это уже не корректировка, а какое-то бессмысленное упрямство. Ведь видно, что перед созданием гиперссылок, присваивать ячейкам значение не нужно. Тем более так, где сначала вводится текст, а затем в ячейке, расположенной под ней, будет создана гиперссылка, ибо Last_Row2 определяется в столбце A, а lastrow для гиперссылки — уже в столбце B, правда без переменной) А инструкция With… предположим, что Вы жить без неё не можете, но нет, при определении номера последней заполненной видимой ячейки и создании гиперссылки — она уже не при делах.
1 |
0 / 0 / 0 Регистрация: 19.09.2013 Сообщений: 18 |
|
12.06.2019, 19:29 [ТС] |
8 |
Да, действительно, так лучше.
0 |
rotten41,
Без обработки ошибок, так как форма может находится за пределами рабочего окна, без учете размеров ячейки больше чем форма и объединеных ячеек, и при активной форме, конда её положение известно. Хотя когда формы нет, все лучше чем ожидал, ссылка просто не работает. Ну и тупым перебором.
Упппс. не учел скролинг рабочией области. Заменил.
Код
=HYPERLINK(«#» & getCentrForm();»центр»)
[vba]
Код
Function getCentrForm() As String
With Application
R = ActiveWindow.VisibleRange.Row
Do While Cells(R, 1).Top < UserForm1.Top + UserForm1.Height / 2 — .Height + .UsableHeight
R = R + 1
Loop
C = ActiveWindow.VisibleRange.Column
Do While Cells(1, C).Left < UserForm1.Left + UserForm1.Width / 2 — .Width + .UsableWidth
C = C + 1
Loop
getCentrForm = Cells(R — 1, C — 1).Address
End With
End Function
[/vba]
I have create with many help a code who create with a user form a new sheet with the name of the client and many other information. And in the first page who resume all name client i have made an hyperlink (column C) who send to queue name of the client. But with the userform a error 424 appears.
Private Sub btnajoutclient_Click()
Dim numFeuilClient As String
Dim prenomFeuilClient As String
Dim telFeuilClient As String
Dim mailFeuilClient As String
Dim AdresseFeuilClient As String
Dim cpFeuilClient As String
Dim villeFeuilClient As String
'RENDRE LES FEUILLES VISIBLES'
Worksheets(2).Visible = True
Worksheets(3).Visible = True
'CREER 2 BOITES POUR AVOIR LES INFOS : NOM ET TEL'
numFeuilClient = frmnouveauclient.TextBoxcasenom
prenomFeuilClient = frmnouveauclient.TextBoxprénom
telFeuilClient = frmnouveauclient.TextBoxcasenumérotel
mailFeuilClient = frmnouveauclient.TextBoxcasemail
AdresseFeuilClient = frmnouveauclient.TextBoxcaseadresse
cpFeuilClient = frmnouveauclient.TextBoxcasecodepostal
villeFeuilClient = frmnouveauclient.TextBoxcaseville
'freezer lécran
Application.ScreenUpdating = False
'SI PAS DE NOM SAISIE ALORS EXIT'
If numFeuilClient = "" Then
Worksheets(2).Visible = False
Worksheets(3).Visible = False
Exit Sub
End If
'ON SUPPRIME LA ZONE SELECTIONNER LA FEUILLE TYPE'
Sheets("FeuilClient").Range("_zonesuprfinal").ClearContents
Sheets("FeuilClient").Copy after:=Sheets(Sheets.Count)
'RENOMMER LA FEUILLE
ActiveSheet.Name = numFeuilClient
'ON MET LE NOM ET LE TEL DANS LES CASES SELECTIONEE DE LA FEUILLE CLIENT'
ActiveSheet.Range("_nomclient").Value = numFeuilClient
ActiveSheet.Range("_telclient").Value = telFeuilClient
ActiveSheet.Range("_prenomclient").Value = prenomFeuilClient
ActiveSheet.Range("_mailclient").Value = mailFeuilClient
ActiveSheet.Range("_adresse").Value = AdresseFeuilClient
ActiveSheet.Range("_codepostal").Value = cpFeuilClient
ActiveSheet.Range("_ville").Value = villeFeuilClient
'Aller sur la feuille fichier client
Sheets(1).Activate
'On trouve une case vide et y met le nom sur le fichier client
Feuil3.Range("A1048000").Select
ActiveCell.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = numFeuilClient
'On trouve une case vide et y met le nom sur le tel du client
Sheets("FichierClient").Range("B1048000").Select
ActiveCell.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = telFeuilClient
'Mettre un hyperlien sur le fichierclient
Sheets("FichierClient").Range("C1048000").Select
ActiveCell.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
Hyperlinks.Add Anchor:=ActiveCell, Address:="", _
SubAddress:="'" & numFeuilClient & "'!A1", TextToDisplay:="Voir Client"
'ON REND INSIVIBLE LES FEUILLES'
Worksheets(2).Visible = False
Worksheets(3).Visible = False
'défreezer l'écran
Application.ScreenUpdating = True
End Sub
marc_s
726k174 gold badges1326 silver badges1449 bronze badges
asked Jun 15, 2021 at 19:02
4
Hyperlinks
needs to be qualified to a Worksheet
The simple fix is change it to
ActiveSheet.HyperLinks.Add ...
That said, there is a lot of opportunity to improve this code. Consider this
Private Sub btnajoutclient_Click()
Dim numFeuilClient As String
Dim prenomFeuilClient As String
Dim telFeuilClient As String
Dim mailFeuilClient As String
Dim AdresseFeuilClient As String
Dim cpFeuilClient As String
Dim villeFeuilClient As String
Dim wsFeuilClient As Worksheet
With ThisWorkbook ' or ActiveWorkbook or specify a workbook
'RENDRE LES FEUILLES VISIBLES'
.Worksheets(2).Visible = True
.Worksheets(3).Visible = True
'CREER 2 BOITES POUR AVOIR LES INFOS : NOM ET TEL'
With frmnouveauclient
numFeuilClient = .TextBoxcasenom
'SI PAS DE NOM SAISIE ALORS EXIT'
If numFeuilClient = vbNullString Then
GoTo CleanUp
End If
prenomFeuilClient = .TextBoxprénom
telFeuilClient = .TextBoxcasenumérotel
mailFeuilClient = .TextBoxcasemail
AdresseFeuilClient = .TextBoxcaseadresse
cpFeuilClient = .TextBoxcasecodepostal
villeFeuilClient = .TextBoxcaseville
End With
'freezer lécran
Application.ScreenUpdating = False
'ON SUPPRIME LA ZONE SELECTIONNER LA FEUILLE TYPE'
.Worksheets("FeuilClient").Range("_zonesuprfinal").ClearContents
Set wsFeuilClient = .Worksheets("FeuilClient").Copy(after:=.Sheets(.Sheets.Count))
'RENOMMER LA FEUILLE
With wsFeuilClient
.Name = numFeuilClient
'ON MET LE NOM ET LE TEL DANS LES CASES SELECTIONEE DE LA FEUILLE CLIENT'
.Range("_nomclient").Value = numFeuilClient
.Range("_telclient").Value = telFeuilClient
.Range("_prenomclient").Value = prenomFeuilClient
.Range("_mailclient").Value = mailFeuilClient
.Range("_adresse").Value = AdresseFeuilClient
.Range("_codepostal").Value = cpFeuilClient
.Range("_ville").Value = villeFeuilClient
End With
'Aller sur la feuille fichier client
With .Sheets(1)
'On trouve une case vide et y met le nom sur le fichier client
.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = numFeuilClient
End With
With .Worksheets("FichierClient")
'On trouve une case vide et y met le nom sur le tel du client
.Cells(.Rows.Count, 2).End(xlUp).Offset(1, 0).Value = numFeuilClient
'Mettre un hyperlien sur le fichierclient
With .Cells(.Rows.Count, 3).End(xlUp).Offset(1, 0)
.Value = numFeuilClient
.Worksheet.Hyperlinks.Add Anchor:=.Cells, Address:=vbNullString, _
SubAddress:="'" & numFeuilClient & "'!A1", TextToDisplay:="Voir Client"
End With
End With
CleanUp:
'ON REND INSIVIBLE LES FEUILLES'
.Worksheets(2).Visible = False
.Worksheets(3).Visible = False
End With
'défreezer l'écran
Application.ScreenUpdating = True
End Sub
answered Jun 15, 2021 at 23:31
chris neilsenchris neilsen
52.2k10 gold badges84 silver badges122 bronze badges
1
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