为什么 .getElementById in VBA return 错误 462?

Why does .getElementById in VBA return error 462?

以下VBA代码returns

Run-time error '462' The remote server machine does not exist or is unavailable

引用行 .getElementById("txt"name").Value = "Arun Banik".

此代码来自 here 但我有一个类似的 objective。

Option Explicit
Const sSiteName = "https://www.encodedna.com/css-tutorials/form/contact-form.htm"

Private Sub CommandButton1_Click()
    Dim oIE As Object
    Dim oHDoc As HTMLDocument
    
    Set oIE = CreateObject("InternetExplorer.Application")
    
    ' Open Internet Explorer Browser and keep it visible.
    With oIE
        .Visible = True
        .Navigate sSiteName
    End With
    
    While oIE.ReadyState <> 4
        DoEvents
    Wend
 
    Set oHDoc = oIE.Document
    
    With oHDoc
        .getElementById("txtName").Value = "Arun Banik"
        .getElementById("txtAge").Value = "35"
        .getElementById("txtEmail").Value = "arun@hotmail.com"
        .getElementById("selCountry").Value = "India"   ' Assign value to the dropdown list in the web form.
        .getElementById("msg").Value = "Hi, I am Arun Banik and this is a test message. :-)"
        
        .getElementById("bt").Click
    End With
End Sub

可能是您没有设置正确的引用。

将“Microsoft Internet Control”和“Microsoft HTML Object Library”添加到您的参考列表中(Alt + F11 > 工具 > 参考...)

您发布的代码没有太多错误。我认为正在发生的事情是代码没有检测到它开始在 While 循环中加载。所以我添加了一个小延迟来尝试解决这个问题。另外,我没有看到需要 document 变量,所以我删除了它。此代码对我有用。

Option Explicit
Const sSiteName = "https://www.encodedna.com/css-tutorials/form/contact-form.htm"

Private Sub CommandButton1_Click()
    Dim oIE As Object
    Set oIE = CreateObject("InternetExplorer.Application")
    
    ' Open Internet Explorer Browser and keep it visible.
    With oIE
        .Visible = True
        .Navigate sSiteName
    End With
    
    'Wait a few seconds for the page to load
    Application.Wait (Now + TimeValue("0:00:02"))
    
    While oIE.ReadyState <> 4
        DoEvents
    Wend
 
    With oIE.Document
        .getElementById("txtName").Value = "Arun Banik"
        .getElementById("txtAge").Value = "35"
        .getElementById("txtEmail").Value = "arun@hotmail.com"
        .getElementById("selCountry").Value = "India"
        .getElementById("msg").Value = "Hi, I am Arun Banik and this is a test message. :-)"
        .getElementById("bt").Click
    End With
End Sub