【发布时间】:2011-11-15 15:11:51
【问题描述】:
我想使用 Excel VBA 阅读网页。我如何执行此任务?有没有可能?
【问题讨论】:
-
请注明您使用的版本!
-
我已切换到 2007 版
标签: vba excel excel-2007 webpage
我想使用 Excel VBA 阅读网页。我如何执行此任务?有没有可能?
【问题讨论】:
标签: vba excel excel-2007 webpage
来自 Excel 2003,是的,这是可能的 - 您可以使用 SHDocVw.InternetExplorer 和 MSHTML.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
【讨论】:
您可以使用 VBA 自动化 IE(通过 Google 提供的大量示例),或者您可以使用 MSHTTP 的实例直接获取页面(网络上也有大量示例)。哪个最适合您的需求将取决于您想要做什么。没有更详细的要求很难说更多。
【讨论】: