您不希望以这种方式设置大量连接(查询表)。如果可能的话,它会很慢。在 8000 个请求时,如果 xmlhttp 没有被阻止或限制,下面的方法将明显更快。如果确实出现变慢/阻塞,则每 x 个请求添加一个小等待。
如果可能的话,使用 xmlhttp 来收集数据。使用css selectors 专门针对实体类型。将值存储在一个数组中,并在最后用循环写出。使用一个类来保存 xmlhttp 对象以提高效率。为您的班级提供包括如何处理未找到的方法(给出的示例)。添加一些进一步的优化,例如给出的是关闭屏幕更新。这假设您的搜索号码在 B2 的 B 列中。下面的代码还对 B 列中是否存在某些内容进行了一些基本检查,并处理存在 1 个或多个数字的情况。
好的代码是模块化的,你想要一个函数返回一些东西,一个子函数来执行操作。单个子/功能不应该完成很多任务。您想使用遵循single responsibility(或接近它)原则的代码轻松调试。
类 clsHTTP
Option Explicit
Private http As Object
Private Sub Class_Initialize()
Set http = CreateObject("MSXML2.XMLHTTP")
End Sub
Public Function GetHTML(ByVal URL As String) As String
Dim sResponse As String
With http
.Open "GET", URL, False
.send
GetHTML = StrConv(.responseBody, vbUnicode)
End With
End Function
Public Function GetEntityType(ByVal html As HTMLDocument) As String
On Error GoTo errhand:
GetEntityType = html.querySelector("a[href*='EntityTypeDescription']").innerText
Exit Function
errhand:
GetEntityType = "Not Found"
End Function
标准模块:
Option Explicit
Public Sub GetInfo()
Dim http As clsHTTP, sResponse As String, lastRow As Long, groupResults(), i As Long, html As HTMLDocument
Set html = New HTMLDocument
Set http = New clsHTTP
Const BASE_URL As String = "http://www.abr.business.gov.au/ABN/View/"
Application.ScreenUpdating = False
With ThisWorkbook.Worksheets("Sheet1")
lastRow = .Cells(.rows.Count, "B").End(xlUp).Row
Select Case lastRow
Case 1
Exit Sub
Case 2
ReDim arr(1, 1): arr(1, 1) = .Range("B2").Value
Case Else
arr = .Range("B2:B" & lastRow).Value
End Select
ReDim groupResults(1 To lastRow - 1)
With http
For i = LBound(arr, 1) To UBound(arr, 1)
If Len(BASE_URL & arr(i, 1)) > Len(BASE_URL) Then
sResponse = .GetHTML(BASE_URL & arr(i, 1))
html.body.innerHTML = sResponse
groupResults(i) = .GetEntityType(html)
sResponse = vbNullString: html.body.innerHTML = vbNullString
End If
Next
End With
For i = LBound(groupResults) To UBound(groupResults)
.Cells(i + 1, "C") = groupResults(i)
Next
End With
Application.ScreenUpdating = True
End Sub
参考资料(VBE> 工具 > 参考资料):
- Microsoft HTML 对象库
CSS 选择器:
我使用实体描述是一个超链接(a 标记)这一事实,并且它的值包含字符串 EntityTypeDescription 以使用带有包含 (*) 运算符的 css 属性 = 值来定位。