如何使用Excel VBA单击href

问题描述 投票:0回答:1

我是VBA的新手,对于如何在Internet Explorer中单击href链接有疑问。源页面上有多个href。我从来没有遇到这个,它给了我一个艰难的时刻!我在这个网站上寻找答案,但决定在这里问。

下面我列出了我的代码,直到我遇到问题,以及Internet Explorer上的源代码。

我评论了我的尝试并列出了我收到的错误。

代码如下:

 Sub ()
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object

User = "User"
Pwd = "Pwd"


Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

URL = "URL.com"

IE.Navigate URL

Do While IE.ReadyState <> 4
  DoEvents
Loop

  IE.Document.getElementById("txtUsername").Value = User
  IE.Document.getElementById("txtPassword").Value = Pwd
  IE.Document.getElementById("btnSubmit").Click


  'IE.getElementByClassName("txtTerms").Click - Runtime Error 438
  'IE.getElementByTagName("Claims Management").Click - Runtime Error 438

'Set HREF = IE.Document.getElementsByClassName("txtTerms")
    'For Each HREF In IE.Document.getElementsByTagName("Claims").Click  - No error occurs, nothing happens.

End Sub

Internet Explorer源代码:

<table id="tblContent">
<tr>
<td class="txtTerms"><a href='href url 1'>Claims</a>

<br>Download<br>Create<br><a class='terms' href='href url 2' 
 target='terms'>Terms</a><br><br></td>
</tr>

我的问题是,如何让VBA只点击'href url 1'?

如果需要任何其他信息,请与我们联系。我为我的VBA级别道歉,但我很高兴了解更多!

谢谢您的帮助!

vba excel-vba internet-explorer href excel-2013
1个回答
1
投票

在HTML中,href<a>(link)类型的属性,它包含绝对路径或相对路径。例如:

<a href="/questions/">Questions</a>

...将显示为“问题”,如果您点击它,将带您到www.stackoverflow.com/questions/。请注意,“www.stackoverflow.com”已自动添加,因为路径是相对的。

<a href="https://www.facebook.com">Facebook</a>

...将显示为“Facebook”,如果您点击它,将带您到www.facebook.com。在这种情况下,路径是绝对的。

虽然您的HTML代码不完整,但我想您要导航的所有链接都包含在table中,其中包含id="tblContent"。如果是这种情况,那么您可以获得所有链接(该表中的tagName == 'a')并将值存储在集合中:

Dim allHREFs As New Collection
Set allLinks = IE.Document.getElementById("tblContent").getElementsByTagName("a")
For Each link In allLinks
    allHREFs.Add link.href
Next link

然后,您可以决定导航它们并逐个执行您必须执行的操作:

For j = 1 To allHREFs.Count
    IE.Navigate URL + allHREFs(j) '<-- I'm assuming hrefs are relative.
    'do your stuff here
Next href
© www.soinside.com 2019 - 2024. All rights reserved.