我正在按照教程使用超链接调用函数。
我的超链接:=HYPERLINK("#addLineClick()","添加新行")
我的功能:
Function addLineClick()
Set addLineClick = Selection
ActiveCell.EntireRow.Copy
With ActiveCell.Offset(1).EntireRow
.Insert
End With
当我在 VBA 窗口中运行我的函数时,它可以工作。
我尝试了上面的方法,当我点击超链接时它没有任何反应。
如果您从工作表上的
HYPERLINK()
公式调用函数,它将被触发,但它受到与从任何其他工作表公式调用时 VBA 函数相同的限制(请参阅 https://support. microsoft.com/en-au/topic/description-of-limitations-of-custom-functions-in-excel-f2f0ce5d-8ea5-6ce7-fddc-79d36192b7a1)。例如来说明一下:这个公式
=HYPERLINK("#tester()", "Test")
调用此 VBA 函数:
Function tester()
With Application.Caller 'the cell with the clicked-on link
Debug.Print "clicked on", .Address 'works
.EntireRow.Insert '## does nothing ##
End With
Set tester = Selection 'must return a valid range for the link destination
End Function
要绕过此限制,您可以使用常规超链接(通过 Insert >> Link)和事件过程。
例如:
在常规模块中:该函数的唯一作用是在单击链接时返回有效的范围引用
'This is a dummy link destination
Function tester()
Set tester = Selection
End Function
在工作表模块中,使用
FollowHyperlink
事件来处理链接上的任何点击。单击使用 HYPERLINK()
创建的链接不会触发此事件,这就是为什么您不能使用它来创建链接。
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
'Figure out what action to take based on the link text
Select Case Target.TextToDisplay
Case "Add Row": Target.Range.Offset(1).EntireRow.Insert
'other actions handled here....
End Select
End Sub
注意,
Workbook_SheetFollowHyperlink
中还有一个 ThisWorkbook
事件,如果您需要响应工作簿中多个不同工作表上的链接,可以使用该事件。