Vba excel get hyperlink

Home / VBA / How to Extract Hyperlink Address (URL) in Excel Using VBA UDF

Let’s say you got an Excel workbook from your colleague where you have a list of hyperlinks in a column. Now from this list, you want to extract all the hyperlink URL addresses.

The manual method is a real pain you need to copy-paste each URL one by one. So the better way is to create a UDF in VBA. And, today I’d like to share with you a simple code for this UDF.

Function GiveMeURL(rng As Range) As String
On Error Resume Next
GiveMeURL = rng.Hyperlinks(1).Address
End Function

How to use this Code

To use this UDF, you need to follow these steps:

  1. Open the visual basic editor from the developer tab or use the keyboard shortcut ALT + F11.
  2. Insert a new module, paste the above code into it and close it.
  3. Now in your worksheet, enter function =GiveMeURL(A1) and hit enter.

It will return the URL from the cell where you have a hyperlink and make sure to download this file from here.

Хитрости »

9 Ноябрь 2012              105472 просмотров


Как получить адрес гиперссылки из ячейки

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

Function Get_Hyperlink_Address(ByVal rCell As Range) As String
    Dim s As String
    If rCell.Hyperlinks.Count = 0 Then
        s = rCell.Formula
        If Mid$(s, 2, 9) = "HYPERLINK" Then
            'такой подход сработает только в случае, если в ячейке записана ссылка текстом
            'но не сработает, если гиперссылка создана из ссылок на ячейки
            '   Get_Hyperlink_Address = Mid$(s, 13, InStr(13, s, Chr(34)) - 13)
            'поэтому используем более сложный, но универсальный вариант
            If s Like "=HYPERLINK*" Then
                'получаем данные первого аргумента и убираем знак =
                s = Split(s, ",")(0)
                s = Mid$(s, 2, Len(s) - 1)
                'на всякий случай добавляем скобку в конец формулы
                'хоть Evaluate должен сработать и без неё
                If Right$(s, 1) <> ")" Then
                    s = s & ")"
                End If
                Get_Hyperlink_Address = Evaluate(s)
            End If
        Else
            Get_Hyperlink_Address = ""
        End If
    Else
        s = rCell.Hyperlinks(1).SubAddress
        If s <> "" Then s = "#" & rCell.Hyperlinks(1).SubAddress
        Get_Hyperlink_Address = rCell.Hyperlinks(rCell.Hyperlinks.Count).Address & s
    End If
End Function

Если впервые сталкиваетесь с подобными функциями настоятельно рекомендую прочитать про то, что это за функции: Что такое функция пользователя(UDF)?.
Доступна функция будет из Мастера функций, категория Определенные пользователем (User Defined). Либо можно напрямую записать в ячейку:=Get_Hyperlink_Address(B1)

Скачать пример

  АдресГиперссылки.xls (66,5 KiB, 12 659 скачиваний)


Решил дополнить статью примером функции, которая позволяет вытащить из ячейки с гиперссылкой подсказку:
Подсказка для гиперссылки

Function Get_Hyperlink_Title(ByVal rCell As Range) As String
    Dim s As String
    If rCell.Hyperlinks.Count = 0 Then
        If Mid$(rCell.Formula, 2, 9) = "HYPERLINK" Then
            Get_Hyperlink_Title = rCell.Text
        Else
            Get_Hyperlink_Title = ""
        End If
    Else
        Get_Hyperlink_Title = rCell.Hyperlinks(1).ScreenTip
    End If
End Function

Так же см.:
Что такое функция пользователя(UDF)?
Что такое гиперссылка?
Текст в гиперссылки
Как массово изменить гиперссылки?


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

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


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



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

Sometimes, you copy webpages. Or just a link. Or you receive an Excel sheet with links in it. In such case, you often want to extract the hyperlink addresses from the cells. There are basically just three options for extracting the hyperlink address from an Excel cell. 

Method 1: Extracting the link addresses manually

VBA, Hyperlink Address, link, address, return, excel, hyperlink

The bad news first: There is no built-in way in Excel to read out a hyperlink, for example with a formula. So the first approach would be typing the hyperlink addresses manually. 

  1. Right click on the cell containing the hyperlink address.
  2. Click on ‘Edit Hyperlink…’.
  3. Copy the link from the address field and paste it wherever you need it.

This method might work for just a couple of links. But if you got more hyperlinks to extract, you might continue with the second or third option.Also, you could try clicking on the link address. That way, a internet browser window opens and you can copy the link address from the address bar.

Method 2: Using VBA for returning the hyperlink address

As we have the bad news covered with the first option, there is also good news: With a short VBA macro it’s still possible to extract the link addresses.

The following macro defines a new excel function. You can use it by typing “=PROFEXHyperlinkAddress(A1)” into your cell (instead of A1 you can of course use any cell reference). After pressing enter, the hyperlink of cell A1 will be displayed. If there is no hyperlink in a cell, nothing will be shown.

Just start by opening the VBA window (Ribbon “Developer”–>”Editor”). Then add a new module (right click in the Project Explorer –> Insert –> Module) and paste the following code into the new macro. If you need more help with VBA macros, please refer to this article.

Function PROFEXHyperlinkAddress(Zelle As Range)
'This function returns a hyperlink address from a cell, for example from a text, copied from the internet

'The cell with the actual hyperlink will be saved in "Zelle"

Dim Link As String
'The link will be saved in the variable "Link"

Application.Volatile
'With "Application.Volatile" you can make sure, that the function will be recalculated once the worksheet is recalculated
'for example, when you press F9 (Windows) or press enter in a cell

If Zelle.Hyperlinks.count Then
'Return the address if there is at least one cell selected
Link = Zelle.Hyperlinks(1).Address

'Return the link address of the first item of the array (in case there are more than one cell selected)

End If

PROFEXHyperlinkAddress = Link
'Return the link

End Function

Method 3: Inserting the link address with ‘Professor Excel Tools’

hyperlink, address, return, get, read, excel, cell, professor
Comfortably get the hyperlink address from Excel cells with Professor Excel Tools

The third option doesn’t involve any VBA. Just download the Excel add-in Professor Excel Tools from below (no sign-up, just activate it within Excel). For getting the link address type =PROFEXHyperlinkAddress(A1) into a cell. Instead of A1 you refer to the cell containing the link.


Professor Excel Tools Box

This function is included in our Excel Add-In ‘Professor Excel Tools’

(No sign-up, download starts directly)


Henrik Schiffner is a freelance business consultant and software developer. He lives and works in Hamburg, Germany. Besides being an Excel enthusiast he loves photography and sports.

Содержание

  1. Hyperlink: 3 Ways of How to Extract the Link from an Excel Cell
  2. Method 1: Extracting the link addresses manually
  3. Method 2: Using VBA for returning the hyperlink address
  4. Method 3: Inserting the link address with ‘Professor Excel Tools’
  5. VBA Hyperlinks
  6. VBA Hyperlinks
  7. Add a Hyperlink with VBA
  8. Adding Text to Display with VBA
  9. Adding a ScreenTip with VBA
  10. Delete a Hyperlink with VBA
  11. Delete all the Hyperlinks in a Worksheet
  12. VBA Coding Made Easy
  13. Follow a Website Hyperlink Using VBA
  14. Follow a Hyperlink to a Folder on Your Drive
  15. Follow a Hyperlink to a File on Your Drive
  16. Go to a Cell in another sheet in the same Workbook
  17. Display all the Hyperlinks in a Worksheet
  18. Display all the Hyperlinks in a Workbook
  19. Using the FollowHyperlink Method to Create Emails
  20. Adding a Hyperlink to an AutoShape in Excel
  21. Inserting the Hyperlink Formula into a Cell Using VBA
  22. Adding a Hyperlink to a Button in Access
  23. Creating a Hyperlink from a Selection in Word
  24. VBA Code Examples Add-in
  25. Hyperlinks in Excel (A Complete Guide + Examples)
  26. How to Insert Hyperlinks in Excel
  27. Manually Type the URL
  28. Insert Using the Dialog Box
  29. Insert Using the HYPERLINK Function
  30. Create a Hyperlink to a Worksheet in the Same Workbook
  31. Create a Hyperlink to a File (in the same or different folders)
  32. Create a Hyperlink to a Folder
  33. Create Hyperlink to an Email Address
  34. Remove Hyperlinks
  35. Manually Remove Hyperlinks
  36. Remove Hyperlinks Using VBA
  37. Prevent Excel from Creating Hyperlinks Automatically
  38. Extract Hyperlink URLs (using VBA)
  39. Extract Hyperlink in the Adjacent Column
  40. Extract Hyperlink Using a Formula (created with VBA)
  41. Find Hyperlinks with Specific Text
  42. Selecting a Cell that has a Hyperlink in Excel
  43. Select the Cell (without opening the URL)
  44. Select a Cell by clicking on the blank space in the cell
  45. Some Practical Example of Using Hyperlink
  46. Example 1 – Create an Index of All Sheets in the Workbook
  47. Example 2 – Create Dynamic Hyperlinks
  48. Example 3 – Quickly Generate Simple Emails Using Hyperlink Function

Sometimes, you copy webpages. Or just a link. Or you receive an Excel sheet with links in it. In such case, you often want to extract the hyperlink addresses from the cells. There are basically just three options for extracting the hyperlink address from an Excel cell.

The bad news first: There is no built-in way in Excel to read out a hyperlink, for example with a formula. So the first approach would be typing the hyperlink addresses manually.

  1. Right click on the cell containing the hyperlink address.
  2. Click on ‘Edit Hyperlink…’.
  3. Copy the link from the address field and paste it wherever you need it.

This method might work for just a couple of links. But if you got more hyperlinks to extract, you might continue with the second or third option.Also, you could try clicking on the link address. That way, a internet browser window opens and you can copy the link address from the address bar.

Method 2: Using VBA for returning the hyperlink address

As we have the bad news covered with the first option, there is also good news: With a short VBA macro it’s still possible to extract the link addresses.

The following macro defines a new excel function. You can use it by typing “=PROFEXHyperlinkAddress(A1)” into your cell (instead of A1 you can of course use any cell reference). After pressing enter, the hyperlink of cell A1 will be displayed. If there is no hyperlink in a cell, nothing will be shown.

Just start by opening the VBA window (Ribbon “Developer”–>”Editor”). Then add a new module (right click in the Project Explorer –> Insert –> Module) and paste the following code into the new macro. If you need more help with VBA macros, please refer to this article.

Method 3: Inserting the link address with ‘Professor Excel Tools’

The third option doesn’t involve any VBA. Just download the Excel add-in Professor Excel Tools from below (no sign-up, just activate it within Excel). For getting the link address type =PROFEXHyperlinkAddress(A1) into a cell. Instead of A1 you refer to the cell containing the link.

This function is included in our Excel Add-In ‘Professor Excel Tools’

(No sign-up, download starts directly)

More than 35,000 users can’t be wrong.

Источник

VBA Hyperlinks

In this Article

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

VBA Hyperlinks

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

Add a Hyperlink with VBA

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

The following code will add a hyperlink to cell A1:

Adding Text to Display with VBA

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

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

Adding a ScreenTip with VBA

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

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

Delete a Hyperlink with VBA

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

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

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

Delete all the Hyperlinks in a Worksheet

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

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

VBA Coding Made Easy

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

Follow a Website Hyperlink Using VBA

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

Follow a Hyperlink to a Folder on Your Drive

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

Follow a Hyperlink to a File on Your Drive

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

Go to a Cell in another sheet in the same Workbook

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

The following code demonstrates how to do this:

Display all the Hyperlinks in a Worksheet

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

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

The results are shown in the Intermediate Window.

Display all the Hyperlinks in a Workbook

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

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

Using the FollowHyperlink Method to Create Emails

You can also create emails using the FollowHyperlink Method.

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

Adding a Hyperlink to an AutoShape in Excel

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

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

The result is:

Inserting the Hyperlink Formula into a Cell Using VBA

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

A quick reminder of the worksheet Hyperlink formula syntax is:

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

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

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

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

Adding a Hyperlink to a Button in Access

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

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

The code for this button would be:

Creating a Hyperlink from a Selection in Word

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

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

VBA Code Examples Add-in

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

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

Источник

Hyperlinks in Excel (A Complete Guide + Examples)

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).

This Tutorial Covers:

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:

  1. Select a cell in which you want to get the hyperlink
  2. Press F2 to get into the edit mode (or double click on the cell).
  3. 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:

  1. Select the cell in which you want the hyperlink
  2. Enter the text that you want to be hyperlinked. In this case, I am using the text ‘Sumit’s Blog’
  3. Click the Insert tab.
  4. Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
  5. In the Insert Hyperlink dialog box, enter the URL in the Address field.
  6. Press the OK button.

This will insert the hyperlink the cell while the text remains the same.

Insert Using the HYPERLINK Function

Another way to insert a link in Excel can be by using the HYPERLINK Function.

Below is the syntax:

  • 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:

  1. Select the cell in which you want the link
  2. Enter the text that you want to be hyperlinked. In this example, I have used the text ‘Link to Sheet2’.
  3. Click the Insert tab.
  4. Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
  5. In the Insert Hyperlink dialog box, select ‘Place in This Document’ option in the left pane.
  6. Enter the cell which you want to hyperlink (I am going with the default A1).
  7. Select the sheet that you want to hyperlink (Sheet2 in this case)
  8. Click OK.

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:

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:

  1. Select the cell in which you want the hyperlink
  2. Click the Insert tab.
  3. Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
  4. In the Insert Hyperlink dialog box, select ‘Existing File or Webpage’ option in the left pane.
  5. Select ‘Current folder’ in the Look in options
  6. 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)
  7. [Optional] Change the Text to Display name if you want to.
  8. 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:

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:

  1. Copy the folder address for which you want to create the hyperlink
  2. Select the cell in which you want the hyperlink
  3. Click the Insert tab.
  4. Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
  5. In the Insert Hyperlink dialog box, paste folder address
  6. 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.

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:

  1. Select the cell in which you want the hyperlink
  2. Click the Insert tab.
  3. Click the links button. This will open the Insert Hyperlink dialog box (You can also use the keyboard shortcut – Control + K).
  4. In the insert dialog box, click on ‘E-mail Address’ in the ‘Link to’ options
  5. Enter the E-mail address and the Subject line
  6. [Optional] Enter the text you want to be displayed in the cell.
  7. 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.

In case you want to have the subject line as well, you can use the below formula:

In the above formula, I have kept the cc and bcc fields as empty, but you can also these emails if needed.

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:

  1. Select the data from which you want to remove hyperlinks.
  2. Right-click on any of the selected cell.
  3. 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:

If you want to remove all the hyperlinks in the worksheet, you can use the below code:

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.

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:

  1. Click the File tab.
  2. Click on Options.
  3. In the Excel Options dialog box, click on ‘Proofing’ in the left pane.
  4. Click on the AutoCorrect Options button.
  5. In the AutoCorrect dialog box, select the ‘AutoFormat As You Type’ tab.
  6. Uncheck the option – ‘Internet and network paths with hyperlinks’
  7. Click OK.
  8. 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.

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:

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:

Note that the above codes wouldn’t work for hyperlinks created using the HYPERLINK function.

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:

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:

  1. 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).
  2. Click the Home tab.
  3. In the Editing group, click on Find and Select
  4. In the drop-down, click on Replace. This will open the Find and Replace dialog box.
  5. In the Find and Replace dialog box, click on the Options button.This will show more options in the dialog box.
  6. In the ‘Find What’ options, click on the little downward pointing arrow in the Format button (as shown below).
  7. Click on the ‘Choose Format From Cell’. This will turn your cursor into a plus icon with a format picker icon.
  8. 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.
  9. Enter 2019 in the ‘Find What’ field and 2020 in the ‘Replace with’ field.
  10. 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).

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:

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.

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:

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

This would open your default email client with the email id abc@trumpexcel.com in the ‘To’ field.

Multiple Recipients Email Id

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

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

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

This would add a single line ‘I love Excel’ to the email message body.

Add Multiple Lines Message in Body

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:

Источник

In this Article

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

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

VBA Hyperlinks

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

Add a Hyperlink with VBA

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

The following code will add a hyperlink to cell A1:

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

The result is:

Add a Hyperlink to a Cell with VBA

Adding Text to Display with VBA

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

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

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

The result is:

Add Text To Display Using VBA

Adding a ScreenTip with VBA

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

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

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

The result is:

Add a ScreenTip to the Hyperlink Using VBA

Delete a Hyperlink with VBA

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

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

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

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

Delete all the Hyperlinks in a Worksheet

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

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

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

VBA Coding Made Easy

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

automacro

Learn More

Follow a Website Hyperlink Using VBA

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

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

Follow a Hyperlink to a Folder on Your Drive

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

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

Follow a Hyperlink to a File on Your Drive

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

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

VBA Programming | Code Generator does work for you!

Go to a Cell in another sheet in the same Workbook

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

The following code demonstrates how to do this:

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

Display all the Hyperlinks in a Worksheet

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

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

Sub ShowAllTheHyperlinksInTheWorksheet()

Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets(1)

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

End Sub

The results are shown in the Intermediate Window.

Show all Hyperlinks in the Intermediate Window Using VBA

Display all the Hyperlinks in a Workbook

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

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

Sub ShowAllTheHyperlinksInTheWorkbook()

Dim ws As Worksheet

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

End Sub

Using the FollowHyperlink Method to Create Emails

You can also create emails using the FollowHyperlink Method.

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

Sub SendEmailUsingHyperlink()

Dim msgLink As String

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

End Sub

The result is:

Using Hyperlinks to Create Emails in VBA

Adding a Hyperlink to an AutoShape in Excel

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

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

Sub AddingAHyperlinkToAShape()

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

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

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

End Sub

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

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

Inserting the Hyperlink Formula into a Cell Using VBA

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

Inserting a Hyperlink Using a Formula with VBA

A quick reminder of the worksheet Hyperlink formula syntax is:

HYPERLINK(link_location, [friendly_name])

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

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

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

Using the Hyperlink Worksheet Formula in VBA

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

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

Adding a Hyperlink to a Button in Access

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

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

Adding a Hyperlink in Access Using VBA

The code for this button would be:

Private Sub buttonOne_Click()

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

End Sub

Creating a Hyperlink from a Selection in Word

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

Adding a Hyperlink using VBA in Word

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

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

The result is:

Adding a Hyperlink to a Selected Text in Word with VBA

Like this post? Please share to your friends:
  • Vba excel get all rows
  • Vba excel function пример
  • Vba excel function as array in
  • Vba excel fso copyfile
  • Vba excel freezepanes закрепить области