약 10 초 동안 매 초마다 파일이 있는지 서버를 확인하고 싶습니다. 파일이 있으면 다운로드하십시오. 그것은 거기에 있지 않습니다. (404) 10 초 동안 최대 10 번까지 다시 시도하십시오. 내가 VBA에없는 보통 코드를 수행하지만, 여기에 간다 .. 내 다운로드 기능이 있습니다루프 내에서 'IXMLHTTPRequest'객체의 열기가 실패합니다.
Function DownloadFile(url As String, fileID As String)
' Setup our path where we will save the downloaded file.
Dim fileSavePath As String
fileSavePath = Environ("USERPROFILE") & "\" & Environ("USERNAME") & "-123-" & fileID & ".xlsx"
' Use Microsoft.XMLHTTP in order to setup a connection.
' https://msdn.microsoft.com/en-us/library/ms535874(v=vs.85).aspx#methods
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("MSXML2.XMLHTTP")
' Pass GET to the Open method in order to start the download of the file.
WinHttpReq.Open "GET", url, False ' method, http verb, async = false
' Send our request: https://msdn.microsoft.com/en-us/library/ms536736(v=vs.85).aspx
WinHttpReq.send
' Reset the url parameter to be the body of the response.
url = WinHttpReq.responseBody
' WinHttpReq.Status holds the HTTP response code.
If WinHttpReq.Status = 200 Then
' Setup an object to hold the binary stream of data (the file).
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
' Set type read only or not: https://msdn.microsoft.com/en-us/library/ms681553(v=vs.85).aspx
oStream.Type = 1
' Write the binary data to WinHttpReq.responseBody
' We can do this because we have confirmed a download via the response code (200).
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile fileSavePath, 2 ' 2 = overwrites the existing file, 1 = will not.
' We are done we the stream, close it.
oStream.Close
Debug.Print "File downloaded! File path: " & fileSavePath
DownloadFile = 1
End If
' Handle if the file doesn't exist.
If WinHttpReq.Status = 404 Then
DownloadFile = 0
End If
End Function
을 그리고 나는 10 번이 기능을 호출하는 하위 있습니다
Sub Callee(url As String, fileID As String)
Dim i As Integer
i = 0
Do While i < 10
If DownloadFile(url, fileID) = 1 Then
Debug.Print "here"
i = 100
Else
Debug.Print fileID & " not found! Try number: " & i
i = i + 1
' We didnt get the response we wanted, so we will wait one second and try again.
Application.Wait (Now + TimeValue("0:00:01"))
End If
Loop
End Sub
내 코드를 404 응답을 받으면 한 번만 실행됩니다. 코드가 루프를 시도 할 때 다시 내가 얻을 : 내 코드는 한 번만 루프를 통해 한 시간을 실행하는 이유
내가 이해가 안 돼요. 나는 Set WinHttpReq = Nothing
에 가비지 콜렉션의 일종을 돌봐주지 않았다. 그러나이 변수가 내 함수에 적용된다는 것을 알았지 만 ...
도움을 주셔서 감사합니다.
당신은 절대적으로 옳습니다!전에 엄격하게 형식화 된 많은 언어를 입력하지 않았고 그 행은 실수입니다. 필자가 타이핑했을 때,''''WinHttpReq.responseBody''로 무엇인가를하고,'''url''을 그 때 의미가있는 것으로 다시 설정하는 아이디어가 있었지만 그것이 어울리지 않을 것이라고 생각합니다. 다른 유형의 변수. 그 점을 지적 해 주셔서 감사합니다! 적어도 나는 (내) 코드에 문제가 없다는 것을 알고있다. Upvoted. – jonathanbell