1

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

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)

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

4

1 回答 1

0

如果你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
于 2013-07-05T07:54:45.060 回答