在Excel VBA中使用HTML文档出现运行时错误91

11 浏览
0 Comments

在Excel VBA中使用HTML文档出现运行时错误91

我有以下代码:

Sub AddSources()
    Dim pubPage As Page
    Dim pubShape As Shape
    Dim hprlink As Hyperlink
    Dim origAddress() As String
    Dim exportFileName As String
    exportFileName = "TestResume"
    Dim linkSource As String
    linkSource = "TestSource2"
    Dim hyperLinkText As TextRange
    For Each pubPage In ActiveDocument.Pages
        For Each pubShape In pubPage.Shapes
            If pubShape.Type = pbTextFrame Then
                For Each hprlink In pubShape.TextFrame.TextRange.Hyperlinks
                    If InStr(hprlink.Address, "http://bleaney.ca") > 0 Then
                        hyperLinkText = hprlink.Range
                        origAddress = Split(hprlink.Address, "?source=")
                        hprlink.Address = origAddress(0) + "?source=" + linkSource
                        hprlink.Range = hyperLinkText
                    End If
                Next hprlink
            End If
        Next pubShape
    Next pubPage
    ThisDocument.ExportAsFixedFormat pbFixedFormatTypePDF, "C:\" + exportFileName + ".pdf"
End Sub

我在hyperLinkText = hprlink.Range这行代码上遇到了“对象变量或With块变量未设置(错误91)”的错误。调试时我可以看到hprlink.Range确实有值。你有什么想法,我做错了什么吗?

0
0 Comments

运行时错误91是Excel VBA中的常见错误,通常在处理HTML文档时出现。这个错误的原因是在代码中没有正确地引用HTML文档的对象。

解决这个问题的方法是使用Set关键字来引用HTML文档对象。具体而言,在这个问题中,我们可以通过以下代码解决这个问题:

Set hyperLinkText = hprlink.Range

这里使用Set是因为TextRange是一个类,因此hyperLinkText是一个对象;如果想要给它赋值,就需要将它指向实际需要的对象。通过使用Set关键字,我们将hyperLinkText对象正确地指向了hprlink.Range对象,从而解决了运行时错误91的问题。

0