填写IE下拉列表的VBA代码有时会崩溃

时间:2015-08-20 00:55:26

标签: vba

以下代码导航到引用页面,然后开始填写一些下拉列表。这是由我在此之后粘贴的功能辅助的。

Sub GetQuote()

rowstart = 2

Do Until Cells(rowstart, 1).Value = ""

Dim IE As Object

Set IE = CreateObject("InternetExplorer.Application")

IE.navigate ("https://www.aami.com.au/secure/comprehensive-car-insurance-   get-a-quote.html")

IE.Visible = True

Application.Wait (Now + TimeValue("00:00:03"))

Do
DoEvents
Loop Until IE.readystate = 4

Set d = IE.Document

SelectOption d, "vehicleYearOfManufactureList", Cells(rowstart, 1).Value    
SelectOption d, "vehicleMakeList", Cells(rowstart, 2).Value
SelectOption d, "vehicleModelList", Cells(rowstart, 3).Value
SelectOption d, "vehicleTransmissionList", Cells(rowstart, 4).Value
SelectOption d, "vehicleNumberOfCylindersList", Cells(rowstart, 5).Value
SelectOption d, "vehicleBodyTypeList", Cells(rowstart, 6).Value

'then there is some more code, but it's irrelevant to my question here

IE.Quit
Loop

End Sub

rowstart变量引用excel电子表格中的一行,我在其中构建了我想要在此引用页面中输入其详细信息的车辆。

因此,当rowstart = 2时,则Cells(rowstart,1)引用单元格A2,在此单元格中将是某些车辆生产年份,例如2012年。

这是链接的功能:

Function SelectOption(doc, strID, strText)

Dim e
Set e = doc.getElementById(strID)

If e Is Nothing Then
    MsgBox "Could not find ID = " & strText
    Exit Function
End If

Dim o
For Each o In e.Options
    If StrComp(o.Text, strText, vbTextCompare) = 0 Then
        o.Selected = True
        Exit For
    End If
Next

If e.SelectedIndex = 0 Then
    MsgBox "Could not set value of " & strID & " to " & strText
    Exit Function
End If

Dim objEvent
Set objEvent = doc.createEvent("HTMLEvents") 
objEvent.initEvent "change", False, True 
e.dispatchEvent objEvent 

Application.Wait (Now + TimeValue("00:00:03"))

SelectOption = True

End Function

我建造的很多车辆都被接受了。但有时会导致程序崩溃。例如,2003,Ford,F250,M,DT6,C / chas(该车辆的元素值)。我已根据源代码检查了这些,以确保它们是此车辆的可用值,并且拼写是正确的,没有空格等。我还手动检查了我可以输入这些并完成报价。我还增加了火灾事件功能的延迟,然后将元素的值更改为略有不同的组合,但无济于事。

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

我不太确定这是一个答案,但它使我能够以某种解决方式处理我遇到的问题。我没有将值设置为电子表格中粘贴的字符串,而是使用了Selected.Index属性。

例如:

IE.Document.GetElementByID("vehicleTransmissionList").SelectedIndex = 2 'In the case of M where it is the second option in drop down list. 1 would have been used for the first option, A

之后我就插入了火灾事件代码,从而删除了我上面粘贴的功能。

相关问题