运行宏的超链接更有趣的方式,看起来是下一个方法(超链接公式)。它不需要任何事件:
- 在单元格中编写超链接公式。这也可以在 VBA 中完成:
Sub testCreateHyperlinkFunction()
'Very important to have # in front of the function name!
Range("A1:A5").Formula = "=HYPERLINK(""#MyFunctionkClick()"", ""Run a function..."")"
End Sub
下一个方法将是一个更引人注目的用途,能够保持已处理范围的初始单元格值(例如“A1:A5”):
Sub testCreateHyperlinkFunctionBis()
Dim rng As Range, arr As Variant, c As Range, i As Long
Set rng = Range("A1:A5")
arr = rng.Value
For i = 1 To UBound(arr, 1)
Range("A" & i).Formula = "=HYPERLINK(""#MyFunctionkClick()"", " & _
IIf(IsNumeric(arr(i, 1)), arr(i, 1), """" & arr(i, 1) & """") & ")"
Next i
End Sub
- 创建要调用的函数(在模块中):
Function MyFunctionkClick()
Set MyFunctionkClick = Selection 'This is required for the link to work properly
MsgBox "The clicked cell addres is " & Selection.row
End Function
请注意确实需要 Set MyFunctionkClick = Selection 行。该函数需要以某种方式知道代码所指的单元格。如果缺少此功能,则会调用该函数两次,并且您会收到“引用无效”错误。
- 单击单元格,函数
MyFunctionkClick() 运行...