我试图编写代码,它将从Excel读取值,在基于内部Web的系统中查找它并将结果存储回Excel中。它读取没有问题的Excel,没有问题打开Internet Explorer,但是当我尝试引用已打开的内容时,出现上述错误。 “ie.Navigate url”这一行起作用,但下一行“Set DOC = ie.Document”会产生错误。任何想法是什么导致这个?这里是我的代码:Internet Explorer VBA自动化错误:调用的对象已与客户端断开连接
Public Sub getClient()
Dim xOpen As Boolean
xOpen = False
Dim row As Long
Dim xL As Excel.Application
Set xL = New Excel.Application
xL.Visible = False
Dim wb As Excel.Workbook
Dim sh As Excel.Worksheet
'Change the name as needed, out put in some facility to input it or
'process multiples...
Dim filename As String
filename = "auditLookup.xlsx"
Set wb = xL.Workbooks.Open(getPath("Audit") + filename)
xOpen = True
Set sh = wb.Sheets(1)
Dim ie As Variant
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
Dim DOC As HTMLDocument
Dim idx As Integer
Dim data As String
Dim links As Variant
Dim lnk As Variant
Dim iRow As Long
iRow = 2 'Assume headers
Dim clientName As String
Dim clientID As String
Dim nameFound As Boolean
Dim idFound As Boolean
Dim url As String
While sh.Cells(iRow, 1) <> ""
'Just in case these IDs are ever prefixed with zeroes, I'm inserting
'some random character in front, but removing it of course when
'processing.
url = "https://.../" + mid(sh.Cells(iRow, 1), 2)
ie.navigate url
Set DOC = ie.Document
'Search td until we find "Name:" then the next td will be the name.
'Then search for "P1 ID (ACES):" and the next td with be that.
Set links = DOC.getElementsByTagName("td")
clientName = ""
clientID = ""
nameFound = False
idFound = False
For Each lnk In links
data = lnk.innerText
If nameFound Then
clientName = data
ElseIf idFound Then
clientID = data
End If
If nameFound And idFound Then
Exit For
End If
If data = "Name:" Then
nameFound = True
ElseIf data = "P1 ID (ACES):" Then
idFound = True
End If
Next
sh.Cells(iRow, 2) = clientName
sh.Cells(iRow, 2) = clientID
iRow = iRow + 1
Wend
Set ie = Nothing
If xOpen Then
wb.Save
Set wb = Nothing
xL.Quit
Set xL = Nothing
Set sh = Nothing
xOpen = False
End If
Exit Sub
看起来也许你需要一个就绪/等待循环? (在这里搜索这个术语所以我相信你会发现实现这个术语的exmaples)这个想法是* navigate *不会立即发生,当页面加载时,浏览器可能无法用于自动化请求, etc. –
不在上面的示例代码中,但我确实在代码中包含以下内容:“Do DoEvents Loop Until ie.ReadyState = READYSTATE_COMPLETE”,它给出了Loop Until行中的相同错误。 –
PKatona
如果我运行调试,并让它坐下来(我可以看到它在IE上出现,我仍然得到错误)。 – PKatona