【发布时间】:2016-09-06 15:03:58
【问题描述】:
我有 15,000 种产品,我需要知道它们是 X、Y 还是 Z。下面的代码在亚马逊上检查产品是否属于 XYZ 类型。
上帝帮助我,它确实有效。唯一的例外是当它搜索亚马逊不再销售的产品时。然后我正在寻找的包含我正在搜索的产品描述的元素 ID 在页面上不存在,并且代码中断行
text = document.getelementbyID("result_0").innertext
出现错误“对象变量或未设置块变量”。
在继续执行其余代码之前,如何检查元素是否存在?
谢谢!
山姆
Sub LetsAutomateIE()
Dim barcode As String
Dim rowe As Integer
Dim document As HTMLDocument
Set ie = CreateObject("InternetExplorer.Application")
Dim Element As HTMLDivElement
Dim text As String
Dim pos As Integer
rowe = 2
While Not IsEmpty(Cells(rowe, 2))
barcode = Cells(rowe, "B").Value
With ie
.Visible = False
.navigate2 "https://www.amazon.co.uk/s/ref=nb_sb_noss_1?url=search-
alias%3Daps&field-keywords=" & barcode
Do Until ie.readyState = 4
Loop
End With
Set document = ie.document
text = document.getElementById("result_0").innerText
If InStr(text, "X") Or InStr(text, "Y") Or InStr(text,
"Z") <> 0 Then pos = 1
If pos <> 0 Then Cells(rowe, 4) = "Y" Else Cells(rowe, 4) = "N"
rowe = rowe + 1
Wend
Set ie = Nothing
End Sub
【问题讨论】:
-
使用错误捕获
-
尝试检查返回的元素是否是一个对象。
set Element = document.getelementbyID("result_0")之类的东西,例如不要返回 InnerText 属性,然后if isObject(Element) then检查它是否作为对象返回。 -
谢谢瑞恩!我应该像设置之前一样调暗元素吗?
-
应该是
Object。 -
感谢您的帮助!
标签: vba excel internet-explorer getelementbyid