简体   繁体   中英

Create Hyperlink to Cell in Another Workbook/CSV VBA

I'm currently working on a script in WorkbookA that notifies of a change in another Workbook (WorkbookB). I would like to add the functionality of being taken to that Workbook if the user would like to see the change. Currently, I'm running the code:

SelRangeA(iRow, 2) = "=HYPERLINK(""[C:\..\WorkbookB.csv]Sheet1!B4"",""CLICK HERE"")"

Which displays the proper Hyperlink in the spreadsheet : Click Here with contents:

=HYPERLINK("[C:\..\WorkbookB.csv]Sheet1!B4","CLICK HERE")

However when I follow the link, it opens the requested Workbook with an error:

Reference is not valid.

Any insight on how to properly reference the required cell? Thanks!

A CSV file won't contain a "Sheet1". The "sheet" name is derived from the name of the file.

So your code needs to be:

=HYPERLINK("[C:\..\WorkbookB.csv]'" & filename & "'!B4","CLICK HERE")

where filename has been set to the base part of the CSV file's filename (ie it needs to equate to "WorkbookB" in your example).

If the link is in another workbook and you want Excel to open it if it isn't already open, you need to specify both the address and the sub-address (kind of like an anchor in an HTML link):

SelRangeA(iRow, 2) = "=HYPERLINK(""C:\Foo.xlsx#[C:\Foo.xlsx]Sheet1!A1"")"

EDIT: Note that for a .csv file, the worksheet name will default to the file name on open:

SelRangeA(iRow, 2) = "=HYPERLINK(""C:\Foo.csv#[C:\Foo.csv]Foo!A1"")"
                                                         '^^^   

One way to do this is to define a name (Formulas->Name Manager) whenever certain cells get changed. For example if the name was defined as "changedcell" you would set the hyperlink as follows:

=HYPERLINK("[C:..\\WorkbookB.csv#changedcell]","CLICK HERE")

Just make sure the scope of the name is set to full workbook if there are multiple worksheets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM