在Excel VBA中使用HTML文档出现运行时错误91
在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
确实有值。你有什么想法,我做错了什么吗?
运行时错误91是Excel VBA中的常见错误,通常在处理HTML文档时出现。这个错误的原因是在代码中没有正确地引用HTML文档的对象。
解决这个问题的方法是使用Set
关键字来引用HTML文档对象。具体而言,在这个问题中,我们可以通过以下代码解决这个问题:
Set hyperLinkText = hprlink.Range
这里使用Set
是因为TextRange
是一个类,因此hyperLinkText
是一个对象;如果想要给它赋值,就需要将它指向实际需要的对象。通过使用Set
关键字,我们将hyperLinkText
对象正确地指向了hprlink.Range
对象,从而解决了运行时错误91的问题。