我的代码很简单。它浏览不同的URL以获取不同的工作表,并从每个URL导入两个数据。
Public Sub import_Data()
Dim ie As InternetExplorer, htmlDoc As HTMLDocument
Dim price As String, volume As String
Dim sheet As Integer
Dim link(14), URL As String
'URL to navigate
link(1) = "https://hk.finance.yahoo.com/q?s=0017.HK&ql=0"
link(2) = "https://hk.finance.yahoo.com/q?s=0151.HK&ql=0"
link(3) = "https://hk.finance.yahoo.com/q?s=0267.HK&ql=0"
link(4) = "https://hk.finance.yahoo.com/q?s=0494.HK&ql=0"
link(5) = "https://hk.finance.yahoo.com/q?s=0700.HK&ql=0"
link(6) = "https://hk.finance.yahoo.com/q?s=0857.HK&ql=0"
link(7) = "https://hk.finance.yahoo.com/q?s=0883.HK&ql=0"
link(8) = "https://hk.finance.yahoo.com/q?s=0939.HK&ql=0"
link(9) = "https://hk.finance.yahoo.com/q?s=0992.HK&ql=0"
link(10) = "https://hk.finance.yahoo.com/q?s=1088.HK&ql=0"
link(11) = "https://hk.finance.yahoo.com/q?s=1398.HK&ql=0"
link(12) = "https://hk.finance.yahoo.com/q?s=1880.HK&ql=0"
link(13) = "https://hk.finance.yahoo.com/q?s=3328.HK&ql=0"
link(14) = "https://hk.finance.yahoo.com/q?s=3988.HK&ql=0"
Set ie = New InternetExplorer
ie.Visible = True
For sheet = 1 To 14
Worksheets(sheet).Activate
'Go to different URL for different worksheets
URL = link(sheet)
ie.navigate URL
Do Until ie.readyState = READYSTATE_COMPLETE
DoEvents
Loop
Set htmlDoc = ie.document
'pull two data from url
price = htmlDoc.getElementsByClassName("time_rtq_ticker")(0).innerText
volume = htmlDoc.getElementsByClassName("yfnc_tabledata1")(9).innerText
Cells(22, 2) = price
Cells(22, 3) = volume
Next sheet
End Sub
奇怪的是,对于每个URL,有时可以成功地导入2个数据,但有时会卡在“DoEvents”行。
代码有什么问题?为什么有时它可以工作,但有时无法完全失败?请问有人能帮我解决这个问题吗?