简体   繁体   English

使用VBA为范围中的每个单元格提供Excel自定义超链接

[英]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 & "' . i.Value"')您缺少&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 & " . 同样值得注意的是, "&i.Value&"编写"&i.Value&"而不是让VBA IDE添加空格,不如自己动手做,例如: " & 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. 您的代码有2个缺陷,您应该添加last &以获取语法正确的公式,并在"&之间添加空格,否则VBA不会认为它是正确的。

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 & "')" 让我们分解一下: "=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' . 公式中的参数为: 'https://somelocation/" & i.Value & "," & i.Value & "'因此此行的输出示例可以为'https://somelocation/1,1' At first, I thought you are writing an URL with a comma, alright..? 起初,我以为您是用逗号编写URL,好吗? But then I looked at the HYPERLINK function in Excel and it requires two parameters. 但是后来我查看了Excel中的HYPERLINK函数,它需要两个参数。 You are only giving one parameter. 您只给出一个参数。 Excel formulas also expect a double quote instead of a single quote. Excel公式还希望使用双引号而不是单引号。 You can escape a double quote in VBA like this "" . 您可以像这样在""在VBA中转义双引号。

The correct line should be: 正确的行应为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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