运行时错误91 - IE对象

时间:2017-05-30 08:10:47

标签: vba excel-vba internet-explorer excel

代码正常工作,但当我尝试关闭IE时,我收到以下错误:

  

"运行时错误91"

Dim IE As Object
Dim shellWins As New ShellWindows
Dim IE_URL As String
Dim Row As Integer

Row = 2

For Each IE In shellWins
    IE_URL = IE.LocationURL
    If IE_URL <> vbNullString Then
        Sheet1.Range("A" & Row) = IE_URL
        row = Row + 1
    End If
Next

Set shellWins = Nothing
Set IE = Nothing

IE.quit

新代码:

Dim shellWins As New ShellWindows
Dim objIE As Object
Dim objIE_TabURL As String
Dim Rowcount As Long

Rowcount = 2

With objIE

    Set objIE = CreateObject("InternetExplorer.Application")

        For Each objIE In shellWins

        objIE_TabURL = objIE.LocationURL

            If objIE_TabURL <> vbNullString And InStr(objIE_TabURL,     
            "file://") = 0 Then

                Rowcount = Rowcount + 1
                sht2.Range("A" & Rowcount) = objIE_TabURL

            End If

        Next

    objIE.Quit

End With

结束新代码

我尝试从IE会话中打开的标签中读取网址,将其导出到工作表中。

我很抱歉,但我是VBA的新手: - (

1 个答案:

答案 0 :(得分:1)

IE实际上并未在任何时候设置为Internet Explorer的实例,您将其用作循环中的对象变体。一旦循环结束,变量就会超出范围,因此无法以您希望的方式再次访问。

如果要在检索URL后关闭IE,请将代码更改为:

For Each IE In shellWins
    IE_URL = IE.LocationURL
    If IE_URL <> vbNullString Then
        Sheet1.Range("A" & Row) = IE_URL
        row = Row + 1
        IE.Quit '// Close IE here, while the variable is still in scope
    End If
Next

请注意,在您的例行程序结束时无需Set IE = Nothing,因为VBA会自动为您管理内存。