在VBA UDF中添加超链接

时间:2014-12-20 23:40:15

标签: excel excel-vba vba

我已经看过如何编辑超链接 - 但我需要在用作自定义公式时添加超链接。

我收到 #VALUE 错误,我不知道为什么。当我尝试在工作表=testit39()

中使用 #VALUE 错误时,有没有人有任何想法?
Public Function testit39() As String
Application.Volatile
Dim rng As range, milestoneinfo As String, milestonesymbol As String

Set rng = Application.Caller
milestoneinfo = "info"
milestonesymbol = "symbol"
If rng.Hyperlinks.Count > 0 Then
    rng.Hyperlinks(1).address = ""
    rng.Hyperlinks(1).screentip = milestoneinfo
    Else
   ThisWorkbook.ActiveSheet.Hyperlinks.Add Anchor:=rng, _
                               address:="", _
                               screentip:=milestoneinfo

    rng.Hyperlinks(1).screentip = milestoneinfo
    End If

 testit39 = milestonesymbol
 End Function

3 个答案:

答案 0 :(得分:2)

由于这个精彩的教程,我找到了一种并不复杂的方法。

http://optionexplicitvba.blogspot.co.uk/2011/04/rollover-b8-ov1.html

所以基本上你把它放在一个超链接中,你就可以自由地做了...

=hyperlink(testit39(), "Wahoo it works!")

答案 1 :(得分:1)

UDF(用户定义的函数)只允许返回一个值,它们可能不会例如affect other cells或做其他操作 当您单步执行代码时,您会看到它在...Hyperlinks.Add行上中止(并返回错误值)。

答案 2 :(得分:0)

以下VBA子代码片段允许添加新的超链接,或编辑指定的样本单元格中存在的内容#34; A1" (为了更清晰起见,您的代码的非必要部分已被删除):

Public Sub AddOrEditHyperlink(milestonesymbol As String)
    Dim rng As Range, milestoneinfo As String
    'test range
    Set rng = Range("A1")
    'sample properties
    milestoneinfo = "info"
    'if Hyperlink exists, display "Edited"
    If rng.Hyperlinks.Count > 0 Then
        rng.Hyperlinks(1).Address = ""
        rng.Hyperlinks(1).ScreenTip = milestoneinfo
        rng.Hyperlinks(1).TextToDisplay = "Edited Hyperlink"
    Else 'if Hyperlink does not exist, add and display "New"
        rng.Hyperlinks.Add _
        Anchor:=rng, _
        Address:="", _
        ScreenTip:=milestoneinfo, _
        TextToDisplay:="New Hyperlink"
    End If
End Sub

您可以从与项目的其余业务逻辑相对应的函数(UDF)中调用此Sub(这有点不清楚):

Public Function testit39() As String
    Application.Volatile
    Dim rng As Range, milestoneinfo As String, milestonesymbol As String
    Call AddOrEditHyperlink("some Symbol")
    testit39 = milestonesymbol
End Function

希望这会有所帮助。最好的问候