VBA IE 在表格内点击

问题描述

我需要点击名为“WS557568037/个人工作区”的 ('href' ) 但没有任何效果。我试过这个代码

'Dim htmlElement As MSHTML.IHTMLElement  For Each htmlElement In HTML.getElementsByClassName("hoverLink")'Debug.Print htmlElement.getAttribute("href") 
htmlElement.Click  Next htmlElement

Dim evt As Object,evt1 As Object Set evt = HTML.createEvent("HTMLEvents") 
evt.initEvent "mouSEOver",True,False IE.Document.querySelector(".hoverLink").dispatchEvent evt IE.Document.querySelector(".hoverLink").Focus  IE.Document.querySelector(".hoverLink").click 

HTML

<div class="tableBody" _tbid="_ygf1bc" style="height: 69px;">
<table class="tableBody" id="_ygf1bc" cellspacing="0" cellpadding="0">

<tbody><tr class="AWTColAlignRow"><td width="1px" style="padding-right: 18px;"></td><td width="" style="padding-right: 27px;"></td><td width="" style="padding-right: 38px;"></td><td width="" style="padding-right: 56px;"></td><td width="" style="padding-right: 50px;"></td><td class="spacer"></td></tr><tr class=" firstRow tableRow1" id="_igbn9d" dr="1" _awtisprimaryrow="1">
<td align="center" class="a-portlet-icon-cell tableBody w-tbl-cell">
<div class="w-doc-portlet-status-hide"></div>
<a id="_a$7voc" href="#" bh="HL" _sf="false"><span class="a-doc-icon-portlet">
<span data-icon="" class="w-icon-default" aria-hidden="true" role="img"></span>

</span>
</a>
</td>


<tr class=" tableRow1" id="_hm6qw" dr="1" _awtisprimaryrow="1">
<td align="center" class="a-portlet-icon-cell tableBody w-tbl-cell">
<div class="w-doc-portlet-status-hide"></div>
<a id="_ayuojd" href="#" bh="HL" _sf="false"><span class="a-doc-icon-portlet">
<span data-icon="" class="w-img" aria-hidden="true" role="img"></span>

</span>
</a>
</td>
<td class="tableBody w-tbl-cell">
<a id="_x2w3t" href="#" bh="HL" _sf="false">WS557568037</a></td>
<td class="tableBody w-tbl-cell">

<a id="_moz9p" href="#" bh="HL" _sf="false" class="hoverLink">Personal Workspace</a>

</td>
<td class="Nowrap tableBody w-tbl-cell">

12/18/2020
</td>
<td class="Nowrap tableBody w-tbl-cell">

<span class="">Active</span>
</td>
</tr>
</tbody></table></div>

解决方法

我尝试检查您的 HTML 代码,发现 WS557568037Personal Workspace 是 2 个不同的链接,并且两个锚元素都包含 ID 属性。

我们可以通过使用它的 ID 属性直接引用链接。

示例 VBA 代码:

Sub demo()

    Dim ie As Object
    Dim lnk,lnk1 As HTMLAnchorElement
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = True
    ie.navigate "https://Your_Website_URL_here..."  'Modify the URL here...

    Do While ie.Busy
        Application.Wait DateAdd("s",1,Now)
    Loop
        
    Set lnk = ie.document.querySelector("a[id='_moz9p']")
    lnk.Click
    
    Set lnk1 = ie.document.querySelector("a[id='_x2w3t']")
    lnk1.Click
    'ie.Quit
End Sub

输出:

enter image description here

此外,您可以尝试根据自己的要求修改代码示例。