Skip to main content

Hyperlinks in VBA


I have programmed in MS Excel using VBA (Visual Basic for Applications) fairly regularly over the past 25+ years. This makes me experienced but not necessarily expert. Frustration over the past several days seems to have demonstrated the lack of expertise, particularly in handling hyperlinks between Excel workbooks.

The project involved building a hyperlink bridge between specific pages/worksheets within two workbooks. The environment wasn’t too difficult since both workbooks would be housed in the same directory. However, the two workbooks would have a parent / child relationship.

The code was designed to build a new control worksheet in the parent workbook and hyperlink it to a specific worksheet and cell range in a child workbook book. The child workbook would be generated entirely in code before being saved.

This didn’t sound too difficult and it wasn’t; until it came to trying to create the hyperlinks between pages of the different workbooks.

The first thing to note is that hyperlink functionality is not native to VBA (for Excel). It is effectively a scripting function for HTML. Also, although the Microsoft Office software elements (e.g. Word, Excel and Access) use identical scripting functions, the SubAddress nomenclature elements vary according to the software used. For example, the SubAddress for Word employs “bookmarks” whereas in Excel we use cell addresses or “names”. Furthermore, the structure of a Word file is fundamentally different from an Excel file. Word files have a single pot, whereas Excel files have multiple worksheets which act as separate pots.

These differences, although apparently small and insignificant, make programming hyperlinks in Excel’s version of VBA frustratingly difficult.

Programming a Hyperlink in Excel

In Excel the hyperlink is programmed for a worksheet or a specific range, but not the workbook. See the example “ThisControlSht.Hyperlinks.Add”, where ThisControlSht is a worksheet variable generated earlier in the program.

The Hyperlinks.Add function has several parameters – Anchor, Address, SubAddress, ScreenTip and TextToDisplay. Each parameter has its own elements which may not be obvious at first glance.

Anchor must be a range. It is the cell in which you wish to place the hyperlink. So either Anchor:=ThisControlSht.Range("MapControlsheet") or Anchor:=ThisControlSht.Range(B5) will work. In this case the cell B5 was named “MapControlSheet”. However, Anchor”=MapControlSheet” does NOT work even though you may appear to be in the correct environment.

Address is usually a website URL but in our case we are linking to another Excel file. For security I employ the full path of the file address and name (including suffix of the file).

SubAddress allows you to specify both the worksheet and particular range of the target. In the Excel environment “names” can be set for the Workbook or specific to a particular Worksheet, but you must ignore that distinction when specifying a SubAddress. You need to specify both the Worksheet and the range. The range can be in the form of a cell address like B5 or a named range like SubAddress:="=DataList_and_MappingIndex!MapListMappingIndex". Note that the sheet name and the range are separated by “!”.

TextToDisplay is an optional parameter and is usually only employed when the cell is empty. However, in the context of this particular program the workbooks / worksheets were being generated in code and therefore all cells were empty unless you had already coded some value to be posted in. In this case I hadn’t. In testing, the program fell over until I had placed some suitable value in the  TextToDisplay.

I would not have got even this far without Excel’s macro recorder. That process generated this code.

Sub Macro2()
'
' Macro2 Macro
'

'
    Windows("My_Test_Book.xlsx").Activate
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
        "My_Test_Book_MapBook.xlsx", SubAddress:="DataList_and_MappingIndex!A1", _
        TextToDisplay:="My_Test_Book_MapBook.xlsx#DataList_and_MappingIndex!A1"
End Sub


Comments

Popular posts from this blog

The Blood Sugar Diet: A Control Approach

Here is a quote from ‘ Get the Gloss ’ , High blood sugar levels - millions of us have it, but many of us don’t know it and it’s led to not just a type 2 diabetes epidemic, but also a rise in  prediabetes , the condition that precedes it. Could calorie restriction help? It worked for medical journalist, Dr  Michael Mosley  and in his book,  The 8-Week Blood Sugar Diet , he shares the science behind it . This website offers a specific diet which, it seems, you should repeat for each day of the 8 weeks. That is one approach but I would get bored very quickly. I guess my likelihood of success under these circumstances would be small. My wife and I wanted controlled variety, but for that we needed to know the calorie content of a wide variety of foods and to measure them out for each meal. I also needed “proof” that I had adhered to the regime throughout the 8 weeks. Hopefully, it would demonstrate how I was moving away from the type 2 diabetes risk zone. Th...

What is a Cell Map?

It is a simplified, colour coded version of an Excel Worksheet. The map shows the structure of the worksheet, its input cells, constants, primary formula and 'named' ranges. The map is designed for spreadsheet developers who work in isolation (i.e. not part of a team), but who, nevertheless, build complex spreadsheet systems. It highlights oddities and inconsistencies within a spreadsheet structure. Excel has its own built-in auditing and mapping tools. Excel's name manager and formula auditing tools These are useful for auditing one formula or one name, but they become overburdened with detail when trying to audit/review a whole worksheet. The ACBA Mapping   [A revised version of the software is now available. Stephen Allen 05 September 2023] utility generates a map of the original spreadsheet and three map keys to aid the interpretation of the detail. For example, I went on strict weight reducing diet last year where I measured the weight/volume of everythin...

A Revised Cell Map!

  In the Blog ' What is a Cell Map? ', I included an image of a Cell Map. On reflection the presentation was muddled. A simpler and clearer design seemed worthwhile. The result below is more clearly rectangular, with the headings for the map, the formula table and the names/validation table matched along the same row. The validation table is new and highlights where user inputs are limited by validation and the nature of the validation criteria. The revised software is available at ACBA-Mapping . In addition, although software is intended to be intuitive and self explanatory, it rarely is. I have created a user group at    MSExcelCellMapping@groups.io   . You are welcome to join and ask questions about the software. https://drive.google.com/file/d/1w3tHk1l-G9LjmCsOqMBkJpE9kaSj0iX_/view?usp=sharing Spreadsheet errors and inconsistensies is a subject that is of concern by professional developers as well as amateurs. The European Spreadsheet Risk Interest Group (EuSpRIG...