Excel VBA:无法获取HTML id的内部文本

时间:2017-08-19 06:44:14

标签: html excel excel-vba vba

嗨:我使用excel从此网页获取值:https://www2.agenciatributaria.gob.es/es13/h/iexmmmfi.html

我怎样才能获得excel VBA的代码来获取NIF,EJF,MOD和CEL的信息?

我尝试使用getelementbyid(" NIF")和" name"但没有结果

谢谢!

Previos主题:Excel VBA: Get inner text of HTML table td

这是我使用的代码:

Sub AEAT()
  Dim IE As Object
  Application.ScreenUpdating = False
  Set IE = CreateObject("InternetExplorer.Application")

  IE.Navigate "https://www2.agenciatributaria.gob.es/es13/h/iexmmmfi.html"

  Application.Wait (Now + TimeValue("0:00:02"))


  IE.Document.getElementById("NIF").Value = Range("A1").Value
  Application.Wait (Now + TimeValue("0:00:01"))

  IE.Document.getElementById("EJF").Value = "2016"
  Application.Wait (Now + TimeValue("0:00:01"))

  IE.Document.getElementById("MOD").Value = "347"
  Application.Wait (Now + TimeValue("0:00:01"))

  IE.Document.getElementById("CEL").Value = Range("a4").Value
  Application.Wait (Now + TimeValue("0:00:01"))

  IE.Document.getElementById("env_button").Click

End Sub

1 个答案:

答案 0 :(得分:0)

好的,所以我在Windows VM中没有Excel,所以我使用VBScript测试了你的代码。所以解决方案应该有效。你有3个问题

  1. 导航并不等待Page加载
  2. 您的网站安装了一个需要先加载的ActiveX控件
  3. 即使你修复#1和#2,你也会得到一个例外"客户端已断开连接"并且该对象将不再可用
  4. <强>解决方案

    将网站添加到IE设置中的可信站点。

    IE Settings

    手动打开IE并安装ActiveX控件

    Sub AEAT()
      Dim IE
      Set IE = CreateObject("InternetExplorer.Application")
      IE.visible = True
      hwnd = ie.hwnd
      IE.Navigate "https://www2.agenciatributaria.gob.es/es13/h/iexmmmfi.html"
      msgbox ("wait")
    
      Set oShell = CreateObject("Shell.Application")
    
      For Each Wnd In oShell.Windows
             If hwnd = Wnd.hwnd Then Set ie = Wnd
      Next 
      IE.Document.getElementById("NIF").Value = "123"
    End Sub
    
    Call AEAT
    

    我已经把msgbox插入等待,但你可以通过在excel中使用以下来自行修复

      Do
        DoEvents
      Loop Until ie.ReadyState = READYSTATE_COMPLETE
    

    PS:来自以下网址的引用

    Internet Explorer VBA Automation Error: The object Invoked has disconnected from its clients

    Error "The object invoked has disconnected from its clients" - automate IE 8 with python and win32com