【问题标题】:Opening workbooks via hyperlink and then using Hyperlink name as workbook reference通过超链接打开工作簿,然后使用超链接名称作为工作簿参考
【发布时间】:2013-07-03 05:05:37
【问题描述】:

我正在尝试获取超链接工作簿名称并将其放入我的代码中。

Sub Workbook()

    Dim vbaname as string
    Dim WBMaster As Workbook, WBSource As Workbook
    Dim WSMaster As Worksheet, WSSource As Worksheet

    Range("b7").Hyperlinks(1).Follow

    'returns the hyperlink text "Vba Source test"
    VbaName = """" & Range("B7").Text & """"

    Set WBSource = Workbooks(VbaName)

我得到一个下标超出范围的错误。有没有另一种方法可以做到这一点。我只是希望能够将超链接文本放入该括号中。

【问题讨论】:

    标签: vba excel reference hyperlink


    【解决方案1】:

    如果你Debug.Print 你的VbaName 它实际上拥有B7 的值,但它是活动窗口(来自超链接的后续窗口)。如果您想从超链接中获取工作簿的名称,请使用此代码

    Sub GetWorkbookName()
        MsgBox "the name of the workbook in the hyperlink is: " & vbCrLf & _
                getWorkbookName(Range("B7").Text)
    End Sub
    
    Private Function getWorkbookName(hyperLink As String) As String
        Dim i&
        For i = 1 To Len(hyperLink)
            If StrComp(Left(Right(hyperLink, i), 1), "\", vbTextCompare) = 0 Then
                getWorkbookName = Right(hyperLink, i - 1)
                Exit For
            End If
        Next i
    End Function
    


    另一方面,我认为您正在尝试从超链接打开工作簿并为其分配引用。你这样做的方式不是正确的方法。我想你可能想考虑这样做:
    Sub Workbook()
    
        Dim wbFromHyperLink As String
        Dim WBSource As Workbook
    
        MsgBox "the name of the workbook in the hyperlink is: " & vbCrLf & _
                getWorkbookName(Range("B7").Text)
    
        wbFromHyperLink = getWorkbookName(Range("B7").Text)
    
        'Range("b7").Hyperlinks(1).Follow
    
        Set WBSource = Workbooks.Open(Range("B7").Text)
    
        ' do not forget to close and free the object
        ' WBSource.Saved = True
        ' WBSource.Close
        ' Set WBSource = Nothing
    End Sub
    
    Private Function getWorkbookName(hyperLink As String) As String
        Dim i&
        For i = 1 To Len(hyperLink)
            If StrComp(Left(Right(hyperLink, i), 1), "\", vbTextCompare) = 0 Then
                getWorkbookName = Right(hyperLink, i - 1)
                Exit For
            End If
        Next i
    End Function
    

    【讨论】:

    • 非常感谢。我的宏将从超链接工作簿中提取数据。它将打开 4 个工作簿,然后执行需要工作簿名称作为语法参考的代码。
    猜你喜欢
    • 2011-06-16
    • 2019-01-16
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 2017-07-31
    • 2021-04-10
    相关资源
    最近更新 更多