Excel, ThisAddIn.vb: why is Application.SheetFollo

2020-05-01 10:13发布

问题:

I'm trying to detect clicked hyperlinks in Excel. The Application.SheetFollowHyperlink Event claims that it will be called "when you click any hyperlink in Microsoft Excel."

However, although it does fire when a cell contains a url like www.google.com, it does not when the cell contains =HYPERLINK("http://www.google.com", "google").

How do I detect clicks to the second type of hyperlink?


For example, a simple excel add in:

Public Class ThisAddIn

    Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup

    End Sub

    Private Sub ThisAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown

    End Sub

    Private Sub Application_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Microsoft.Office.Interop.Excel.Hyperlink) Handles Application.SheetFollowHyperlink
        MsgBox("Hyperlink Clicked")
    End Sub

A message box containing "Hyperlink Clicked" will appear when you click a cell containing www.google.com but not a cell containing =HYPERLINK("http://www.google.com", "google").

回答1:

I seem to have solved the issue, although I'm not sure why the following works while the code I used above doesn't:

Private HyperlinkFollower As Excel.DocEvents_FollowHyperlinkEventHandler

Private Sub CalledWhenHyperlinkClicked(ByVal Target As Excel.Hyperlink)
    Dim w As Microsoft.Office.Interop.Excel.Window = Globals.ThisAddIn.Application.ActiveWindow
    MsgBox("hyperlink clicked")
End Sub

EventDel_HyperlinkFollower = New Excel.DocEvents_FollowHyperlinkEventHandler(AddressOf CalledWhenHyperlinkClicked)

AddHandler worksheet.FollowHyperlink, EventDel_HyperlinkFollower