Fab*_*elo 1 excel vba excel-vba
我正在使用宏从网站获取信息:
Sub get_prices()
Dim IE As Object
Dim URL As String
Dim cell As Range
Dim rng As Range
Set rng = Range("A2", Range("A1048576").End(xlUp))
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
For Each cell In rng.Cells
comeco:
On Error GoTo pau:
URL = Cells(1, 2) & cell.Text & "?utm_source=teste" & Rnd
IE.Navigate (URL)
Do
DoEvents
Loop Until IE.READYSTATE = 4
Application.Wait (Now + TimeValue("00:00:05"))
Cells(cell.Row, 2) = Mid(IE.Document.GetElementById("ctl00_Conteudo_ctl01_precoPorValue").innertext, 3)
Cells(cell.Row, 2).Formula = _
WorksheetFunction.Substitute(WorksheetFunction.Substitute(Cells(cell.Row, 2), ".", ""), ",", ".")
Next
pau:
IE.Quit
Set IE = Nothing
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
GoTo comeco:
End Sub
Run Code Online (Sandbox Code Playgroud)
问题是,我的Excel有时会"丢失IE对象",并在以下行中收到错误消息"对象已被请求":
Cells(cell.Row, 2) = Mid(IE.Document.GetElementById("ctl00_Conteudo_ctl01_precoPorValue").innertext, 3)
通常,我只是调试代码,并创建一个新行,如:
Set IE = CreateObject("InternetExplorer.Application")
然后我恢复宏.
Bud我想做一些更健壮的东西,每当发生错误时,它会关闭IE然后重新打开它.
我正在尝试使用
on error goto
但它只在第一次发生错误时才起作用,如果再次发生则不会进入错误部分.
谁能帮我?
如果您尝试添加错误处理以捕获缺少的InternetExplorer实例,请尝试以下操作.在违规行之前和之后的代码中添加错误语句.
On Error Goto IE_missing 'This changes error handling from the default popup error message to instead direct VBA to jump to the IE_missing label and try the code there.
Cells(cell.Row, 2) = Mid(IE.Document.GetElementById("ctl00_Conteudo_ctl01_precoPorValue").innertext, 3)
On Error Goto 0 'This resets the error handling back to the default so you don't accidentally catch errors in other parts of the code
Run Code Online (Sandbox Code Playgroud)
然后在代码的末尾放置一个部分,如下所示:
Exit Sub 'This keeps the rest of the Sub's code from accidentally running down into the error section.
IE_missing: 'When the specific line above errors, VBA directs execution here
Set IE = CreateObject("InternetExplorer.Application")
Resume 'Now that the IE instance has been set again, retry the offending line of code
Run Code Online (Sandbox Code Playgroud)