[英]Message box not always visible
我有以下VBA代碼,該代碼旨在從Web下載文件,給我一條消息“從...下載數據”,下載后給我一條消息“下載到...”。 這是我的代碼:
Sub DownloadFileFromWeb()
Dim IE As Object
Dim links As Variant, lnk As Variant
Dim download_path As String
download_path = "\\xxxxx\Save Raw File here.xls"
Set IE = CreateObject("InternetExplorer.Application")
IE.Navigate "http://www.hkma.gov.hk/eng/market-data-and-statistics/monthly-statistical-bulletin/table.shtml#section2" 'load web page
While IE.Busy
DoEvents 'wait until IE is done loading page.
Wend
Set links = IE.document.getElementsByTagName("a")
For Each lnk In links
If Len(lnk.href) > 4 And Right(lnk.href, 4) = ".xls" And InStr(1, lnk.href, "http://www.hkma.gov.hk/media/eng/doc/market-data-and-statistics/monthly-statistical-bulletin/T080102.xls") <> 0 Then
MsgBox "Downloading Data from " & lnk.href
Download_File lnk.href, download_path
MsgBox "Downloaded to - " & download_path
Exit For
End If
Next
End Sub
Function Download_File(ByVal vWebFile As String, ByVal vLocalFile As String) As Boolean
Dim oXMLHTTP As Object, i As Long, vFF As Long, oResp() As Byte
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.Open "GET", vWebFile, False 'Open socket to get the website
oXMLHTTP.Send 'send request
'Wait for request to finish
Do While oXMLHTTP.readyState <> 4
DoEvents
Loop
oResp = oXMLHTTP.responseBody 'Returns the results as a byte array
'Create local file and save results to it
vFF = FreeFile
If Dir(vLocalFile) <> "" Then Kill vLocalFile
Open vLocalFile For Binary As #vFF
Put #vFF, , oResp
Close #vFF
'Clear memory
Set oXMLHTTP = Nothing
End Function
我遇到的問題是,在大多數情況下,我不會出現任何消息框,同時也沒有任何下載。 您能否一直幫助我以獲得消息框?
非常感謝你!
我在最后測試了您的代碼,但看不到任何錯誤。 我已經下載了一百次,而且它沒有損壞。 但是,我做了一些小的修改。
將主子例程更改為以下內容:
Sub DownloadFileFromWeb()
Dim IE As Object
Dim links As Variant, lnk As Variant
Dim download_path As String
download_path = "C:\...\SavedFile.xls" 'Modify.
Set IE = CreateObject("InternetExplorer.Application")
IE.Navigate "http://www.hkma.gov.hk/eng/market-data-and-statistics/monthly-statistical-bulletin/table.shtml#section8" 'load web page
While IE.Busy
DoEvents 'wait until IE is done loading page.
Wend
Set links = IE.document.getElementsByTagName("a")
For Each lnk In links
If Len(lnk.href) > 4 And Right(lnk.href, 4) = ".xls" And InStr(1, lnk.href, "T080102.xls") <> 0 Then
If MsgBox("Downloading Data from " & lnk.href, vbOKOnly) = vbOK Then
Download_File lnk.href, download_path
MsgBox "Downloaded to - " & download_path
Exit For
End If
End If
Next
End Sub
基本上,我只是更改了一件事:消息框將在下載文件之前等待您的輸入。 請注意If MsgBox(...) = vbOKOnly
我是如何做的。 這樣,它將等待您的輸入而不會中斷。
網址也做了些微更改。 將section2
更改為section8
,因為這是您想要的表(恕不影響任何內容,恕我直言)。
讓我們知道是否有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.