我将研究实际的XMLHTTP请求作为更快的检索方法。目前,虽然有点不寻常,但请看到你的答案有结构性的重写,并附上一些注释。
注:
1)将IE对象移出循环并在循环前可见。其他一些不受循环影响的变量也一样,例如baseurl。
2)将过去52周的高、低值选择减少到使用CSS选择器以适当的元素为目标。
3)在适当情况下与语句一起使用,例如用于确定lastrowstocktickerpe
4)取消不必要的额外等待
5)移除集合=当超出范围时,将取消引用任何不需要的对象。
Option Explicit
Public Sub Retrieve_PE_Low_High()
Dim DownloadInfoSheet As Worksheet, OutputSheet As Worksheet
Dim Stockticker As Long, lastrowStockTickerPE As Long
Dim baseURL As String, searchResultsURL As String
Dim HTMLDoc As HTMLDocument, oIE As InternetExplorer
Set DownloadInfoSheet = ActiveWorkbook.Worksheets("DownloadInfo") 'Sheet to retrieve stockticker from
Set OutputSheet = ActiveWorkbook.Worksheets("Output") 'Where data will be assigned
Set oIE = New InternetExplorer
baseURL = DownloadInfoSheet.Cells(3, "A")
With DownloadInfoSheet
lastrowStockTickerPE = .Cells(.Rows.Count, "D").End(xlUp).Row
End With
With oIE
.Visible = True
For Stockticker = lastrowStockTickerPE To lastrowStockTickerPE '<==presumably your endpoint is not always the same as start
searchResultsURL = baseURL & DownloadInfoSheet.Cells(Stockticker, "C").Value 'Add the ticker symbol to the original URL link, example "https://www.nasdaq.com/symbol" + "ADP" = "https://www.nasdaq.com/symbol/ADP"
.Navigate2 searchResultsURL
While .Busy Or .readyState < 4: DoEvents: Wend
Set HTMLDoc = .document
Dim high As Object, low As Object
With HTMLDoc
On Error Resume Next
Set high = .querySelector(".infoTable.trading-activitiy tr + tr td:last-child")
Set low = .querySelector(".infoTable.trading-activitiy tr + tr + tr td:last-child")
Debug.Print high.innerText, low.innerText
On Error GoTo 0
If high Is Nothing Or low Is Nothing Then
'dummy
Else
'other code to write to sheet
End If
End With
Set high = Nothing: low = Nothing
Next Stockticker
.Quit
End With
End Sub
一个示例xmlhttp请求,您可以使用上面的IDEA将其适应到循环中。有趣的是,针对元素的CSS选择器必须稍微调整一下。
Option Explicit
Public Sub GetInfo()
Dim sResponse As String, html As HTMLDocument, high As Object, low As Object
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.nasdaq.com/symbol/AAPL", False
.send
html.body.innerHTML = StrConv(.responseBody, vbUnicode)
End With
On Error Resume Next
Set high = html.querySelector(".infoTable.trading-activitiy tr + tr td + td")
Set low = html.querySelector(".infoTable.trading-activitiy tr + tr + tr td + td")
Debug.Print high.innerText, low.innerText
On Error GoTo 0
End Sub