Running VBA from a HYPERLINK()

前端 未结 4 1339
生来不讨喜
生来不讨喜 2020-11-30 13:43

I\'m trying to let my users send email easily from their Excel spreadsheets, which they like to use as front-ends for data entry and manipulation. My intention is to write a

4条回答
  •  情深已故
    2020-11-30 14:08

    Using hyperlinks to trigger actions is a bit tricky:

    • HYPERLINK() links don't trigger Worksheet_FollowHyperlink event handlers
    • When using the "Insert Hyperlink"-type links you need a valid target address, and this can result in the selection jumping around when the user clicks on a link.

    Here's one approach - place this code in the worksheet module:

    Option Explicit
    
    Dim oldAdd As String
    
    'When a link is clicked, this gets triggered first
    '   if the clicked cell has a hyperlink, remember its address
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Dim c As Range
    
        'only want single-cell selections...
        If Target.Cells.CountLarge > 1 Then
            Exit Sub
        Else
            'cell has a link? Remember the address...
            If Target.Hyperlinks.Count > 0 Then
                oldAdd = Target.Address()
            End If
        End If
    End Sub
    
    'This is called immediately after the SelectionChange event,
    '  so we can use the stored address to reset the selection back
    '  to the clicked cell, instead of wherever its link was pointing to
    Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    
        Dim c As Range
    
        If oldAdd <> "" Then
            Set c = Me.Range(oldAdd)
            c.Select 'undo any navigation
            'Here you could switch on the link text if you have
            '   links which need to trigger different actions
            If c.Value = "Send Mail" Then
                MsgBox "Sending mail!"
                'generateEmail [use values from cells relative to c]
            End If
        End If
    
    End Sub
    

    Assumes all links point to the same sheet as the one the links are on.

提交回复
热议问题