使用VBA将数据从Web复制到excel

时间:2018-07-30 12:46:23

标签: html excel excel-vba web-scraping

我有一个网页,需要我的代码才能复制页面中的全部数据,然后将其复制到excel工作表中,但现在还没有发生。我的Excel工作表即将完全空白。我认为^a功能在IE上无法正常工作,无法选择数据然后将其复制。

非常感谢您的帮助。下面是我正在使用的代码。

Sub Webdata()

    Dim assetname As String, country As String, area As String, region As String, pth As String, folname As Variant, assetname1 As String

    Website = "http://website.com/"
    Set myIE = CreateObject("InternetExplorer.Application")
    myIE.Navigate source
    myIE.Visible = True
    Application.Wait Now + TimeSerial(0, 0, 10)
    SendKeys "^a"
    Application.Wait Now + TimeSerial(0, 0, 2)
    SendKeys "^c"
    Application.Wait Now + TimeSerial(0, 0, 2)
    Sheets.Add
    ActiveSheet.Name = "Webdata"
    ActiveSheet.Paste
    Application.Wait Now + TimeSerial(0, 0, 2)

    Range("A1").Select
    Cells.Find(What:="Api Number", After:=ActiveCell, LookIn:= _
               xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
               xlNext, MatchCase:=False, SearchFormat:=False).Activate

    ActiveCell.Offset(1, 0).Select
    Selection.Copy
    Sheets("Sheet1").Activate
    Range("C2").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                           :=False, Transpose:=False
    Application.CutCopyMode = False
    myIE.Quit

    Set myIE = Nothing
    Err.Clear
    Sheets("Webdata").Select
    ActiveSheet.Delete

End Sub

1 个答案:

答案 0 :(得分:1)

那个表是一团糟,所以与其花时间完善如何将表写出到工作表,不如我通常那样,即循环表行和行内的表单元格,我会坚持复制表的想法但请使用剪贴板,并使用.SetText,而不是SendKeys。 感兴趣的表位于嵌套框架内,因此您必须首先进行协商。

Set hTable = .frames(2).document.getElementsByTagName("table")(0)

代码:

Option Explicit
Public Sub GetInfo()
    Dim IE As New InternetExplorer, html As HTMLDocument, hTable As HTMLTable, clipboard As Object
    Application.ScreenUpdating = False
    With IE
        .Visible = True
        .navigate "http://pipeline.wyo.gov/Wellapi.cfm?oops=IDxxxxx&nAPINO=xxxxxx" '<==Input your personal URL here 
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set html = .document
        With html
            Set hTable = .frames(2).document.getElementsByTagName("table")(0)
            Set clipboard = New MSForms.DataObject
            clipboard.SetText hTable.outerHTML
            clipboard.PutInClipboard
            ActiveSheet.Cells(1, 1).PasteSpecial
        End With
        .Quit
    End With
    Application.ScreenUpdating = True
End Sub

参考:

VBE>工具>参考:

  1. Microsoft Forms 2.0对象库
  2. HTML对象库
  3. Internet Explorer控件