如何用VBA读取IE表格文本?

时间:2014-02-10 21:38:58

标签: excel vba excel-vba internet-explorer

我正在尝试编写vba代码以遵循此过程:

  1. 填写并提交自动网络表单(打开一个新网页,回答http://ec.europa.eu/taxation_customs/vies/?locale=en

  2. 查找新网页的地址(因为我需要阅读此内容)

  3. 读取html表格的特定单元格(公司名称)

  4. 您可以尝试使用增值税号FR(法国)和27435044714手动提交。 它将返回包含公司名称的页面。

    基本上我很难提取公司名称。

    第1步非常有效,独立于第2步和第2步。 3。 第2步和第3步是在同一个Sub:

    宏从步骤2开始(找到打开的网页)

    Sub recup()
    Dim SWs As SHDocVw.ShellWindows, IE As SHDocVw.InternetExplorer 
    'Establish link to IE application
    Set SWs = New SHDocVw.ShellWindows
    
    For Each IE In SWs
        If Left(IE.LocationURL, 4) <> "http" Then
        GoTo autre
        End If
        Address = IE.LocationURL
        GoTo vabene 'avoid explorer windows/etc this way
    autre:
    Next
    vabene:
    

    然后,我继续执行步骤3以提取文本。

    IE.Visible = True
    Dim xobj
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    Set xobj =IE.Document.getElementById("vatResponseFormTable").getElementsByClassName("labelStyle").Item(3)
    Set xobj = xobj.getElementsByTagName("td").Item(0)
    result = xobj.innerText
    Set xobj = Nothing
    IE.Quit
    Set IE = Nothing
    End Sub
    

    我的问题:宏停在线上(运行时错误91):

      

    result = xobj.innerText

    这似乎来自上一行

      

    设置xobj = xobj.getElementsByTagName(“td”)。Item(0)

    我在网络和这个论坛上搜索了很多(直到这一步它才帮助我)。如果你可以帮助我,那将节省我的一周!

1 个答案:

答案 0 :(得分:1)

试试这个

Sub getData()

'~~~~Variable declaration~~~~'
    Dim IE As Object
    Dim country As Object
    Dim num As Object
    Dim btn As Object
    Dim tlb As Object, td As Object

    Set IE = CreateObject("InternetExplorer.Application")

    IE.Visible = False
    IE.navigate "http://ec.europa.eu/taxation_customs/vies/?locale=en"

'Wait till page is loaded
    Do While IE.readystate <> 4
        DoEvents
    Loop


    Set country = IE.document.getelementbyid("countryCombobox")
    country.Value = "FR" 'set the value for Member state


'Pause the code for 5 sec
    Application.Wait Now + TimeSerial(0, 0, 5)

'
    Set num = IE.document.getelementbyid("number")
    num.Value = "27435044714" 'set the Vat number


    Application.Wait Now + TimeSerial(0, 0, 5)


    Set btn = IE.document.getelementbyid("submit")
    btn.Click ' click the verify button

'Wait till page is loaded
    Do While IE.readystate <> 4: DoEvents: Loop

'Pause the code for 5 sec
        Application.Wait Now + TimeSerial(0, 0, 10)

        Set tbl = IE.document.getelementbyid("vatResponseFormTable")

        For Each td In tbl.getelementsbytagname("td")
            If td.innerText = "Name" Then
                MsgBox "Name : " & td.NextSibling.innerText
            ElseIf td.innerText = "Address" Then
                MsgBox "Address : " & td.NextSibling.innerText
            ElseIf td.innerText = "Consultation Number" Then
                MsgBox "Consultation Number : " & td.NextSibling.innerText
            End If

        Next


        IE.Quit
        Set IE = Nothing
 End Sub