dojo Excel VBA -单击名称相同的按钮

r8xiu3jd  于 2022-12-16  发布在  Dojo
关注(0)|答案(1)|浏览(192)

我有一个网站,所有的按钮都有相同的类名,按钮的唯一区别部分是“数据dojo附件点”。
我正在尝试单击该按钮或选择该字段并输入值。

<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

有人知道我如何选择正确的按钮来点击吗?
先谢了!

u1ehiz5o

u1ehiz5o1#

您可以使用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"的目标节点。

相关问题