简体   繁体   English

使用 VBA 单击 IE 网页中的链接/按钮

[英]Using VBA to click on a link/button in an IE web page

I have read a lot of information on using VBA to click on a link in IE, but I cannot get it to work in my case.我已经阅读了很多关于使用 VBA 单击 IE 中的链接的信息,但我无法让它在我的情况下工作。 The relevant HTML code is as follows:相关的HTML代码如下:

<div id="LinkButton_3" widgetId="LinkButton_3">
    <a class="Row_Icon" data-dojo-attach-point="linkNode" data-dojo-attach-event="onClick:_onLinkButtonClicked">Company XYZ. - #12345</a>
</div>

The VBA code I have tried, with 3 different attempts noted, is as follows:我尝试过的 VBA 代码,有 3 次不同的尝试,如下所示:

Dim ieApp           As SHDocVw.InternetExplorer
Dim ieDoc           As MSHTML.HTMLDocument
Dim button          As HTMLInputButtonElement
Dim div             As HTMLDivElement

' Create a new instance of IE
    Set ieApp = New InternetExplorer

' Uncomment this line for debugging purposes.
    ieApp.Visible = True
' Go to the page we're interested in.
    ieApp.Navigate "MyURL.com"


    Do While ieApp.Busy: DoEvents: Loop
    Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop

    Set ieDoc = ieApp.Document
' Try #1.
' Nothing happened on the web page after these 3 lines were executed.
        Set button = ieDoc.getElementById("LinkButton_3")
        button.Focus
        button.Click
' Try #2
' Nothing happens - button is not clicked.
        Set div = ieDoc.getElementById("LinkButton_3")
        div.FireEvent "onClick"
' Try #3
' Nothing happens - button is not clicked.
        div.Click

' Close the instance of IE.
        ieApp.Quit
' Clean up.
        Set ieApp = Nothing
        Set ieDoc = Nothing

Any thoughts on what I might be doing wrong or other suggestions would greatly be appreciated.关于我可能做错了什么或其他建议的任何想法将不胜感激。

TMc TMc

You can also use a CSS querySelector of #LinkButton_3 a .您还可以使用#LinkButton_3 a的 CSS querySelector。 This is the a tag within the element with id LinkButton_3 .这是id LinkButton_3的元素中的a标记。 The "#" means id . “#”表示id The " a" means a tag within. “a”表示a标签。

CSS 查询

.querySelector method belong to the HTMLDocument. .querySelector方法属于 HTMLDocument。

You can do:你可以做:

ieDoc.querySelector("#LinkButton_3 a").Click
<div id="LinkButton_3" widgetId="LinkButton_3">
    <a class="Row_Icon" data-dojo-attach-point="linkNode" data-dojo-attach-event="onClick:_onLinkButtonClicked">Company XYZ. - #12345</a>
</div>

What you want to click on is the anchor (a) tag, not the div.您要点击的是锚点 (a) 标签,而不是 div。 So, you can find the div with its id and then click on its one and only child with因此,您可以找到带有 id 的 div,然后单击其唯一的孩子

button.Children(0).Click

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM