【问题标题】:Reading Web Pages using Excel VBA使用 Excel VBA 读取网页
【发布时间】:2011-11-15 15:11:51
【问题描述】:

我想使用 Excel VBA 阅读网页。我如何执行此任务?有没有可能?

【问题讨论】:

  • 请注明您使用的版本!
  • 我已切换到 2007 版

标签: vba excel excel-2007 webpage


【解决方案1】:

来自 Excel 2003,是的,这是可能的 - 您可以使用 SHDocVw.InternetExplorerMSHTML.HTMLDocument 对象来调用网页,控制 DOM 对象并与之交互。创建对 Microsoft HTML 对象库 (...\system32\MSHTML.TLB) 和 Microsoft Internet Control (...\system32\ieframe.dll) 的引用后,您可以使用以下示例:

Sub Test()
Dim Browser As SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument

    Set Browser = New SHDocVw.InternetExplorer                     ' create a browser
    Browser.Visible = True                                         ' make it visible
    Application.StatusBar = ".... opening page"
    Browser.navigate "http://www.google.com"                       ' navigate to page
    WaitForBrowser Browser, 10                                     ' wait for completion or timeout

    Application.StatusBar = "gaining control over DOM object"
    Set HTMLDoc = Browser.document                                 ' load the DOM object
    WaitForBrowser Browser, 10

    ' at this point you can start working with the DOM object. Usefull functions are
    ' With HTMLDoc
    '     .getElementByID(string)
    '     .getElementsByTagName(string)
    '     .getElementsByName(string)
    '     .getAttribute(string)
    '     .setAttribute string, string     .... to change field values, click a button etc.
    ' End With

    Application.StatusBar = ""                                      ' time to clean up
    Browser.Quit
    Set HTMLDoc = Nothing
    Set Browser = Nothing
End Sub

Sub WaitForBrowser(Browser As SHDocVw.InternetExplorer, Optional TimeOut As Single = 10)
Dim MyTime As Single

    MyTime = Timer
    Do While Browser.Busy Or (Timer <= MyTime + TimeOut)
        DoEvents
    Loop

    ' if browser still busy after timeout, give up
    If Browser.Busy Then
        MsgBox "I waited for " & Timer - MyTime & " seconds, but browser still busy" & vbCrLf & _
               "I give up now!"
        End
    End If
End Sub

【讨论】:

  • 非常感谢,太好了>
【解决方案2】:

您可以使用 VBA 自动化 IE(通过 Google 提供的大量示例),或者您可以使用 MSHTTP 的实例直接获取页面(网络上也有大量示例)。哪个最适合您的需求将取决于您想要做什么。没有更详细的要求很难说更多。

【讨论】:

猜你喜欢
  • 2014-11-25
  • 1970-01-01
  • 2019-04-03
  • 2017-11-04
  • 2020-12-05
  • 2016-09-12
  • 1970-01-01
  • 2021-10-18
  • 2020-11-30
相关资源
最近更新 更多