简体   繁体   中英

Excel custom hyperlink for each cell in range using VBA

I have a module that removes all formulas from an entire sheet and then, it should, create a hyperlink formula on each cell using the cell value.

Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Test")

ws1.Range("B33:F533").Value = ws1.Range("B33:F533").Value


For Each i In ws1.Range("B33:B533")

i.Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"

Next


End Sub

EDIT: It's now working perfectly. Thanks For all the help!

i.Formula = "=HYPERLINK('https://somelocation/"&i.Value&","& i.Value"')"

Has an error in the formula. At the i.Value"') you are missing & , i.Value & "' . The correct one, that 'compiles', is added below:

i.Formula = "=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"

Also it is worth noting that instead of writing "&i.Value&" and let the VBA IDE add the spaces, it is better to do it yourself, eg: " & i.Value & " .

You're code has 2 flaws, you should add the last & to get a syntax correct formula, and add spaces between the " and & , or else VBA won't see it is right.

Edit; a third flaw:

The line to create the formula is wrong too. Let's break it down: "=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"

The parameter in the formula would be: 'https://somelocation/" & i.Value & "," & i.Value & "' so an output example of this line could be 'https://somelocation/1,1' . At first, I thought you are writing an URL with a comma, alright..? But then I looked at the HYPERLINK function in Excel and it requires two parameters. You are only giving one parameter. Excel formulas also expect a double quote instead of a single quote. You can escape a double quote in VBA like this "" .

The correct line should be:

i.Cells(1, 1).Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"

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