Vba excel открыть гиперссылку

 

axis86

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

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

#1

11.04.2013 17:53:24

Здравствуйте! Подскажите, пожалуйста, как с помощью макроса можно открыть гиперссылку такого вида:

Код
=ГИПЕРССЫЛКА("."&D9&".JPG";D9)

Пробовал так:

Код
Sub FollowHypelink()   
On Error Resume Next   
    If InStr(1, ActiveCell.Formula, "hyperlink", vbTextCompare) > 0 Then   
        ThisWorkbook.FollowHyperlink Evaluate(ActiveCell.Formula)   
    Else   
        ActiveCell.Hyperlinks(1).Follow   
    End If   
End Sub
 

Обычные гиперссылки открываются, а формулы-гиперссылки — нет.
Заранее благодарен!

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

  • test1.xlsx (10.66 КБ)
  • 637024.jpg (31.87 КБ)
  • 772185.jpg (46.36 КБ)

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

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

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

axis86

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

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

Вроде всё сделал как описано в статье, но не работает почему-то. Даже в этом примере, который в статье, не могу макросом открыть гиперссылку созданную формулой, а обычная открывается…
Может можно как-то по другому сделать? Суть такова, что мне нужно открывать гиперссылки созданные формулой клавиатурой, не важно каким сочетанием или комбинацией клавиш.

Изменено: axis8613.04.2013 22:35:50

 

EducatedFool

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

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

#4

13.04.2013 18:11:51

Это смотрели?

http://excelvba.ru/code/FormulaHyperlinks#comment-1083

Код
Sub ПереходПоГиперссылкеИзАктивнойЯчейки()

    ' получаем гиперссылку из активной ячейки листа
   URL$ = FormulaHyperlink(ActiveCell)
    
    ' если гиперссылка найдена - переходим по ней
   If Len(URL$) Then ThisWorkbook.FollowHyperlink URL$
    
End Sub

Function FormulaHyperlink(ByRef cell As Range) As String
    If cell.HasFormula And (cell.Hyperlinks.Count = 0) Then
        If cell.Formula Like "=HYPERLINK*" Then
            FormulaHyperlink = Evaluate(Mid$(Split(cell.Formula, ",")(0), 12))
        End If
    End If
End Function
 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

#5

13.04.2013 18:21:21

Я не понимаю, в чем сложности применения кода по данной мной ссылке? Добавили функцию к себе и переходите так:

Код
Sub FollowHypelink()
    On Error Resume Next
    ThisWorkbook.FollowHyperlink Get_Hyperlink_Address(ActiveCell)
End Sub

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Дима, в его случае это не работает, — Evaluate надо применять к начинке функции,
как у меня: Evaluate(Mid$(Split(cell.Formula, «,»)(0), 12))

а не как у ТС: Evaluate(ActiveCell.Formula)
и как у тебя (вообще не применяется)

Потому что у него ссылка составная — из нескольких ячеек собирается.

 

axis86

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

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

#7

15.04.2013 11:41:31

Цитата
EducatedFool пишет:
Это смотрели?
http://excelvba.ru/code/FormulaHyperlinks#comment-1083

Код
 Sub ПереходПоГиперссылкеИзАктивнойЯчейки()

    ' получаем гиперссылку из активной ячейки листа
   URL$ = FormulaHyperlink(ActiveCell)
    
    ' если гиперссылка найдена - переходим по ней
   If Len(URL$) Then ThisWorkbook.FollowHyperlink URL$
    
End Sub

Function FormulaHyperlink(ByRef cell As Range) As String
    If cell.HasFormula And (cell.Hyperlinks.Count = 0) Then
        If cell.Formula Like "=HYPERLINK*" Then
            FormulaHyperlink = Evaluate(Mid$(Split(cell.Formula, ",")(0), 12))
        End If
    End If
End Function 

Спасибо, огромное! Работает как часы!

Если можно еще маленький вопрос: как можно в 2007 эклесе сделать чтобы картинки из ссылок открывались в стандартной программе просмотра изображений, а не в ИЕ? Уже весь интернет перерыл, ничего не помогает  :(

Уже решил проблему самостоятельно  :)
Еще раз, Большой Спасибо!

Изменено: axis8615.04.2013 12:05:49

 

Юрий М

Модератор

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

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

#8

15.04.2013 12:14:31

axis86, а в данном случае цитирование обязательно? Не пробовали ПРОСТО ответить?

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

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

Синтаксис

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

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

Параметры

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sub Primer()

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

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

Set myRange = Range(«A1:G10»)

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

n = myRange.Cells.Count

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

    For i = 1 To n

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

            s = myRange.Cells(i).Address

            Exit For

        End If

    Next

MsgBox s

End Sub

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


In this Article

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

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

VBA Hyperlinks

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

Add a Hyperlink with VBA

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

The following code will add a hyperlink to cell A1:

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

The result is:

Add a Hyperlink to a Cell with VBA

Adding Text to Display with VBA

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

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

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

The result is:

Add Text To Display Using VBA

Adding a ScreenTip with VBA

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

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

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

The result is:

Add a ScreenTip to the Hyperlink Using VBA

Delete a Hyperlink with VBA

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

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

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

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

Delete all the Hyperlinks in a Worksheet

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

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

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

VBA Coding Made Easy

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

automacro

Learn More

Follow a Website Hyperlink Using VBA

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

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

Follow a Hyperlink to a Folder on Your Drive

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

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

Follow a Hyperlink to a File on Your Drive

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

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

VBA Programming | Code Generator does work for you!

Go to a Cell in another sheet in the same Workbook

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

The following code demonstrates how to do this:

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

Display all the Hyperlinks in a Worksheet

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

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

Sub ShowAllTheHyperlinksInTheWorksheet()

Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets(1)

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

End Sub

The results are shown in the Intermediate Window.

Show all Hyperlinks in the Intermediate Window Using VBA

Display all the Hyperlinks in a Workbook

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

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

Sub ShowAllTheHyperlinksInTheWorkbook()

Dim ws As Worksheet

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

End Sub

Using the FollowHyperlink Method to Create Emails

You can also create emails using the FollowHyperlink Method.

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

Sub SendEmailUsingHyperlink()

Dim msgLink As String

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

End Sub

The result is:

Using Hyperlinks to Create Emails in VBA

Adding a Hyperlink to an AutoShape in Excel

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

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

Sub AddingAHyperlinkToAShape()

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

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

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

End Sub

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

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

Inserting the Hyperlink Formula into a Cell Using VBA

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

Inserting a Hyperlink Using a Formula with VBA

A quick reminder of the worksheet Hyperlink formula syntax is:

HYPERLINK(link_location, [friendly_name])

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

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

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

Using the Hyperlink Worksheet Formula in VBA

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

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

Adding a Hyperlink to a Button in Access

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

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

Adding a Hyperlink in Access Using VBA

The code for this button would be:

Private Sub buttonOne_Click()

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

End Sub

Creating a Hyperlink from a Selection in Word

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

Adding a Hyperlink using VBA in Word

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

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

The result is:

Adding a Hyperlink to a Selected Text in Word with VBA

I have an excel file. In the first sheet there are rows of hyperlinks (Relative files paths = files are located next to the excel file).

In the VBA, I will obtain the cell that contain hyperlinks. How can I open the file which is followed by hyperlink in the VBA? Actually I want to open the hyperlink (open the file actually)

Community's user avatar

asked Oct 31, 2016 at 13:45

Mosi's user avatar

3

If the hyperlink in the worksheet is in a =hyperlink() formula we:

  • grab the formula
  • parse it to get the url
  • follow the hyperlink:

Here is the code:

Sub ClickByVba()
    ary = Split(ActiveCell.Formula, Chr(34))
    ActiveWorkbook.FollowHyperlink Address:=ary(1)
End Sub

enter image description here

This will work for both links to the web and links to files.
If the link is to a file, the file will be opened (if not already open) and the jump will be made.

answered Oct 31, 2016 at 14:11

Gary's Student's user avatar

Gary’s StudentGary’s Student

95.3k9 gold badges58 silver badges98 bronze badges

2

As I commented on Gary´s answer, the ActiveWorkbook.FollowHyperlink method works, but it will ask for your credentials every time you open the link, if your website requires a login.

If you wish to open a website and have your credentials saved, you can use this other function:

Sub OpenHyperlink(ByVal link As String)
   'Escape chars that cmd.exe uses
    link = Replace(link, "^", "^^")
    link = Replace(link, "|", "^|")
    link = Replace(link, "&", "^&")
    'Open default web browser
    Shell "CMD.EXE /C START " & link, vbHide
End Sub

answered Mar 29, 2019 at 2:51

cyberponk's user avatar

cyberponkcyberponk

1,51617 silver badges19 bronze badges

Have a look at the Hyperlink object reference:

https://msdn.microsoft.com/en-us/library/office/ff835563.aspx

You should be able to open the file with the .Follow method, or if that doesn’t work you can always grab the .Address property and pass that to the Workbooks.Open method.

Also bookmark the Excel Object Model Reference for future use :)

I don’t think this works on formula hyperlinks, though, so if that’s your situation then instead, do:

Sub h()
    Dim cl As Range
    Dim h As String
    Set cl = Range("E13") 'Modify to the cell containing your =HYPERLINK formula
    h = Replace(cl.Formula, "=HYPERLINK(", "")
    h = Replace(h, ")", "")
    h = Replace(h, Chr(34), "")
    h = Split(h, ",")(0)

    Dim wb As Workbook
    Set wb = Workbooks.Open(h)
End Sub

answered Oct 31, 2016 at 13:52

David Zemens's user avatar

David ZemensDavid Zemens

52.8k11 gold badges79 silver badges129 bronze badges

2

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

Открыть гиперссылку без мыши с помощью кода VBA


Открыть гиперссылку без мыши с помощью кода VBA

Здесь вы можете вставить простой код, а затем создать ярлык на основе этого кода, сделайте следующее:

1. Удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модулии вставьте следующий код в окно модуля.

Код VBA: открыть гиперссылку с помощью сочетаний клавиш:

Sub SimulateMouseClickonHyperlink()
ActiveCell.Hyperlinks(1).Follow
End Sub 

3. Затем сохраните и закройте окно кода и нажмите Alt + F8 для открытия Макрос В диалоговом окне выберите кодовое имя, которое вы только что вставили, а затем щелкните Опции кнопку в Параметры макроса в диалоговом окне введите нужную комбинацию клавиш, см. снимок экрана:

4, Затем нажмите OK и закройте диалоговые окна, с этого момента, когда вы выбираете ячейку гиперссылки, и нажимаете Ctrl + т ключи, гиперссылка будет открыта сразу.


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (6)


Оценок пока нет. Оцените первым!

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