1

我在 excel 2010 和 internet explorer 8 和 Vista 中使用 vba。下面的代码可用于访问远程网站并发布表单。在结果页面上,代码应单击“获取估计值”按钮。相反,我收到此错误“对象变量或未设置块变量”。代码中突出显示的问题行是“estimate = ieApp.document.getElementById("btnRequestEstimates")”。

我认为问题的一部分可能是不起作用的按钮是不属于表单的提交按钮。我还想知道是否需要在单击第二个按钮之前重置变量。错误消息暗示这是一个限定问题,但我认为这是在这种情况下限定元素的一种非常标准的方法。这些是我一直在谷歌搜索无济于事的一些事情,我不确定问题是什么。

Sub btn_version()

Dim ieApp As Object
Dim ieDoc As Object
Dim ieForm As Object
Dim ieObj As Object
Dim URL As String
Dim estimate As Object

URL = "http://www.craft-e-corner.com/p-2688-new-testament-cricut-cartridge.aspx"
Set ieApp = CreateObject("InternetExplorer.Application")
ieApp.Visible = True
ieApp.navigate URL
While ieApp.Busy Or ieApp.readyState <> 4: DoEvents: Wend

Set ieDoc = ieApp.document
Set ieForm = ieDoc.forms(1)
For Each ieObj In ieForm.Elements
If ieObj.ClassName = "AddToCartButton" Then
ieObj.Click
End If
Next ieObj

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
While ieApp.Busy Or ieApp.readyState <> 4: DoEvents: Wend
estimate = ieApp.document.getElementById("btnRequestEstimates")
estimate.submit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

End Sub
4

1 回答 1

3

下面的代码结合了您的 xmlhttp 代码,该代码来自自动提交带有 vba 和 xmlhttp 的网站上的帖子表单(以便您更好地控制POST,即Set ieDoc = ieApp.document在我们的问题中跳过您的部分),然后单击此页面"btnRequestEstimates的最终 URl 上的按钮

Sub Scrape2()

Dim objIE As Object
Dim xmlhttp As Object
Dim ieButton As Object
Dim strResponse As String
Dim strUrl As String

strUrl = "http://www.craft-e-corner.com/addtocart.aspx?returnurl=showproduct.aspx%3fProductID%3d2688%26SEName%3dnew-testament-cricut-cartridge"
Set objIE = CreateObject("InternetExplorer.Application")
objIE.navigate "about:blank"
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")

'~~> Indicates that page that will receive the request and the type of request being submitted
xmlhttp.Open "POST", "http://www.craft-e-corner.com/addtocart.aspx?returnurl=showproduct.aspx%3fProductID%3d2688%26SEName%3dnew-testament-cricut-cartridge", False
'~~> Indicate that the body of the request contains form data
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'~~> Send the data as name/value pairs
xmlhttp.Send "Quantity=1&VariantID=2705&ProductID=2688"
strResponse = xmlhttp.responseText
objIE.navigate strUrl
objIE.Visible = True

Do While objIE.readystate <> 4
    DoEvents
Loop

objIE.document.Write strResponse

Set xmlhttp = Nothing
Set ieButton = objIE.document.getelementbyid("btnRequestEstimates")
ieButton.Click

End Sub
于 2012-01-12T02:28:20.670 回答