【问题标题】:Where to find VBA functions for working with internet explorer在哪里可以找到使用 Internet Explorer 的 VBA 函数
【发布时间】:2012-07-05 06:08:57
【问题描述】:

我正在开发一个 VBA 函数来访问网页、查找单个 HTML 元素并显示其内容。这是我目前所拥有的。

Function WebTableToSheet(webpage As String, tag As String, count As Integer) As String


  'Tested using IE7,  Excel 2000 SP1, and Windows XP
  Dim objIE As Object
  Dim varTables, varTable, document
  Dim allTags, tags
  Dim varRows, varRow
  Dim varCells, varCell
  Dim lngRow As Long, lngColumn As Long
  Dim strBuffer As String

  Set objIE = CreateObject("InternetExplorer.Application")

 'Setup
  With objIE
    .AddressBar = False
    .StatusBar = False
    .MenuBar = False
    .Toolbar = 0
    .Visible = True
    .Navigate webpage
  End With

  'Load webpage
  While objIE.Busy
  Wend
  While objIE.document.ReadyState <> "complete"
  Wend


  varTable = objIE.document.All

  allTags = objIE.document.All.tags(tag)

  WebTableToSheet = allTags.Item(count)

  Debug.Print "Testing function"




Cleanup:
    Set varCell = Nothing: Set varCells = Nothing
    Set varRow = Nothing: Set varRows = Nothing
    Set varTable = Nothing: Set varTables = Nothing
    objIE.Quit
    Set objIE = Nothing
End Function

我可以打开 InternetExplorer,进入功能中指定的网页,但是当我尝试搜索特定标签时,它似乎失败了。我在搜索 Microsoft VBA Internet Explorer 文档时遇到了麻烦,并且知道哪些变量和方法可用于此任务?

【问题讨论】:

  • 您可以在此处使用getElementsByTagNamegetElementById(取决于您是按元素ID 还是类型搜索)。由于您从这些方法中获取集合或对象,因此您还应该使用 Set allTags = ...
  • 如果您想进行数据抓取,那么值得一读stackoverflow.com/questions/8798260/…

标签: excel vba internet-explorer


【解决方案1】:

我建议设置对 shdocvw.dll 和 Microsoft HTML 对象库的引用。在 XP 中,shdocvw.dll 在您的 system32 文件夹中,HTML 对象库应该在您的引用列表中。我目前只能访问 XP,因此您必须搜索您正在使用的任何其他版本的 Windows。然后在您的代码中,您可以执行以下操作:

Dim IE as SHDocVw.InternetExplorer
Dim doc as HTMLDocument
Dim el as IHTMLElement
Set IE = new SHDocVw.InternetExplorer

With IE
  .navigate "some.webpage.com"
  .visible = true
End With

Do
  'Nothing
Loop Until IE.readyState = READYSTATE_COMPLETE ' = 4

Set doc = IE.Document
Set el = doc.getElementById("someElementId")
If Not el Is Nothing Then
  MsgBox el.innerText
End If

【讨论】:

  • 当然,设置库引用不是必要的,但它肯定会让遍历 HTML DOM 变得更容易,特别是如果你不熟悉它。
【解决方案2】:

团队, IE网页完全加载检查使用下面提到的代码

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

Do Until IE.Busy = False
   DoEvents
Loop

【讨论】:

    【解决方案3】:
    ieApp.Navigate "Https://duckduckgo.com/"
    
    'Wait for Internet Explorer to finish loading
    Do While ieApp.Busy: DoEvents: Loop
    Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
    
    ieApp.Document.getelementbyid("search_form_input_homepage").Value = "Gajendra Santosh"
    ieApp.Document.getelementbyid("search_button_homepage").Click
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 2016-03-16
      相关资源
      最近更新 更多