添加子程序到超链接无法正常工作

时间:2017-10-17 17:14:02

标签: excel-vba hyperlink vba excel

我正在尝试添加一个链接到名称的超链接,该名称将链接到子程序。当用户单击超链接名称时,将调用子例程。

现在,我可以超链接一个单元格,我有一些代码可以显示一个消息框,但是当我点击超链接的单元格时,没有任何内容出现。

"Assign macro to hyperlink" tutorial I'm using

简化代码:

Sub Main()
    Call SetHyperlink
End Sub

Sub SetHyperlink()
    Range("A6").Select
    ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="$A$6", TextToDisplay:="TEST"  
End Sub

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    'Check if the Target Address is same as you have given
    'In the above example i have taken A4 Cell, so I am
    'Comparing this with $A$4

    If Target.Range.Address = "$A$6" Then
        'Write your all VBA Code, which you want to execute
        'Or Call the function or Macro which you have
        'written or recorded.
        MsgBox "Write your Code here to be executed"
        Exit Sub
    End If
End Sub

我对vba仍然很新,所以如果它显而易见,请让我知道推理。提前谢谢!

1 个答案:

答案 0 :(得分:2)

使用工作簿模块,使用此代码检查超链接文本,然后根据超链接选择调用宏。

    Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
    Select Case Target.TextToDisplay
    Case "hi"
        MsgBox "Hi"
    Case "Oranges"
        MsgBox "You selected oranges"
    Case "Banana"
        MsgBox "Banana"
    Case "Trees"
        MsgBox "Tree"
    End Select

End Sub

enter image description here