2014-12-20 105 views
1

我已經看到了如何編輯超鏈接 - 但我需要一個自定義公式中使用時添加一個超鏈接。在VBA UDF添加超鏈接

我得到一個#VALUE錯誤,我不知道爲什麼。有沒有人有,爲什麼我得到一個#VALUE錯誤的任何想法,當我嘗試使用它在一張紙上=testit39()

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 

回答

1

的UDF(用戶定義函數)只允許返回一個值,他們可能不會例如affect other cells或做其他操作。
當你通過單步執行代碼,你會看到它中止對...Hyperlinks.Add系法(和返回錯誤值)。

+0

它實際上可能但需要複雜的解決方法。 http://stackoverflow.com/questions/8520732/i-dont-want-my-excel-add-in-to-return-an-array-instead-i-need-a-udf-to-change – brettdj

+0

並不複雜如果您使用的超級鏈接功能.. http://optionexplicitvba.blogspot.co.uk/2011/04/rollover-b8-ov1.html – Wickey312

0

以下VBA子代碼片段允許添加新的超鏈接,或編輯現有的指定樣本細胞「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)調用此子:

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 

希望這會有所幫助。最好的問候