找不到 `elementId` 时提示

Prompt when `elementId` not found

我有 VBA 通过点击 elementId 浏览网页的代码。

当找到 elementId 时,它提供了所需的结果。

我的问题是,找不到elementId时没有错误提示。代码一直持续到最后。


例如代码:

Ie.visible = True
Ie.navigate "www.abc.com"

Ie.document.getElementbyId("btk").click

在这里,我试图点击按钮 btk

但是网页上没有这个按钮。
我原以为我的代码会崩溃,但它一直持续到最后。
代码中没有使用错误处理。

据我了解,您希望在调用点击事件之前检查网页中代表按钮btkelementId是否真的存在。

一种方法是创建一个对象(我将其称为 buttonElement)并尝试将其设置为 ID 为 btk 的按钮(如果不存在则使用 getElementById("btk")在网页中,对象 buttonElement 将是 Nothing,但如果它存在,该对象将获得对该按钮的引用

Dim buttonElement As HtmlElement
Set buttonElement = Ie.document.getElementById("btk")
'
If Not (buttonElement Is Nothing) Then
    buttonElement.click
Else:
   '
   'Do something else, buttonElement with id btk not found
End If

我建议您尝试使用最新的更新来更新您的 Windows OS 和 MS Office,这可能会帮助您解决此问题。

我已经用 MS Office 2016 Windows 10 OS 上的简单代码测试了这个问题。

我可以看到,如果代码在页面上找不到该元素,则会生成错误。

测试代码:

Sub demo()

    Dim i As Long
    Dim URL As String
    Dim IE As Object
    
    Set IE = CreateObject("InternetExplorer.Application")
     
    IE.Visible = True
    
    URL = "http://localhost/86.html"
   
    IE.Navigate URL
  
    Do While IE.ReadyState = 4: DoEvents: Loop
    Do Until IE.ReadyState = 4: DoEvents: Loop
 
    IE.document.getElementById("abc").Click
    
    Set IE = Nothing
    
End Sub

输出:

感谢@Scott Holtzman、@tdmsoares、@Deepak-MSFT 回复我的查询。

不幸的是,应用程序升级 OS 不在我的控制范围内,所以我选择使用 if 语句。

使用 if 语句,我在找不到按钮时引发了自定义错误以获取 运行 时间错误。

当我知道需要点击的elementid时,使用了下面的方法。

Dim buttonElement As HtmlElement
Set buttonElement = Ie.document.getElementById("btk")

If Not (buttonElement Is Nothing) Then
    buttonElement.click
Else:
   Err.raise vbObjectError+515,,”The sign in button was not found"
   
End If

当需要通过元素搜索找出要点击的按钮时,使用下面的方法

Dim htmla as mshtml.ihtmlelement
Dim htmlas as mshtml.ihtmlelementcollection

Signin= 0
For each htmla in htmlas
If htmla.getattribute(“classname”) = “hero_button" Anand htmla.innertext =”Sign in" then
signin= signin+1
Htmla.click
Exit for
Next htmla
If signin<>1 then
Err.raise vbObjectError +515,,” The sign in button was not found"
End if
```