Excel VBA - 当按钮具有相同名称时单击按钮

时间:2016-03-27 14:32:41

标签: excel excel-vba internet-explorer dom dojo vba

我有一个网站,其中所有按钮都具有相同的类名,按钮的唯一区别部分是“data-dojo-attach-point”。

我试图点击该按钮或选择该字段并输入值。

<div class="btn btn-default" type="button" data-dojo-attach-point="searchAddress">Search</div>

<div class="btn btn-default" type="button" data-dojo-attach-point="buildToAddress">Build to Address</div>

即。像这样

    Set element = .document.getElementsByClassName("btn btn-default")
element.Item(0).Click

有谁知道如何选择正确的按钮进行点击?

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用以下示例中的CSS选择器.querySelector()

Sub Test()

    Dim objNode As Object

    With CreateObject("InternetExplorer.Application")
        .Navigate "file://C:\tmp.htm"
        .Visible = True
        Do While .Busy Or Not .readyState = 4: DoEvents: Loop ' wait IE
        Do Until .document.readyState = "complete": DoEvents: Loop ' wait document
        Set objNode = .document.querySelector("div[data-dojo-attach-point='buildToAddress']")
        Debug.Print objNode.innerText ' "Build to Address"
        objNode.Click
        .Quit
    End With

End Sub

我使用以下内容保存C:\tmp.htm进行测试:

<html>
    <title>test</title>
    <body>
        <div class="btn btn-default" type="button" data-dojo-attach-point="searchAddress">Search</div>
        <div class="btn btn-default" type="button" data-dojo-attach-point="buildToAddress">Build to Address</div>
    </body>
</html>

以下是另一个示例,使用.getElementsByClassName().getAttribute()

Sub Test()

    Dim colNodes As Object
    Dim objNode As Object
    Dim strTarget As String

    strTarget = "buildToAddress"
    With CreateObject("InternetExplorer.Application")
        .Navigate "file://C:\tmp.htm"
        .Visible = True
        Do While .Busy Or Not .readyState = 4: DoEvents: Loop ' wait IE
        Do Until .document.readyState = "complete": DoEvents: Loop ' wait document
        Set colNodes = .document.getElementsByClassName("btn btn-default")
        For Each objNode In colNodes
            If objNode.getAttribute("data-dojo-attach-point") = strTarget Then Exit For
        Next
        If Not objNode Is Nothing Then
            Debug.Print objNode.innerText ' "Build to Address"
            objNode.Click
        End If
        .Quit
    End With

End Sub

正如您在立即窗口中看到的那样objNode.innerText是“Build to Address”,对应于具有data-dojo-attach-point="buildToAddress"的目标节点。