当我们要处理一个文件时,通常最好先进行测试以确保文件存在,如果我们需要从某个网站下载文件,那么需要先验证这个网址URL是否存在,那么可以通过下列的函数来进行校验。
可以将下列的代码放到新建的模块中,然后可以在窗体的事件中进行调用,例如: WinHTTP_URLExist("http://www.accessoft.com")
Function WinHTTP_URLExist(ByVal sURL As String) As Boolean
On Error GoTo Error_Handler
#Const WinHTTP_EarlyBind = False 'True => Early Binding / False => Late Binding
#If WinHTTP_EarlyBind = True Then
Dim oWinHttp As WinHttp.WinHttpRequest
Set oWinHttp = New WinHttp.WinHttpRequest
#Else
Dim oWinHttp As Object
Const WinHttpRequestOption_UserAgentString = 0
Const WinHttpRequestOption_EnableRedirects = 6
Set oWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
#End If
Dim lStatusCode As Integer
With oWinHttp
.Option(WinHttpRequestOption_EnableRedirects) = False
.Option(WinHttpRequestOption_UserAgentString) = "curl"
.SetTimeouts 3000, 5000, 3000, 5000
.Open "HEAD", sURL, False
.Send
lStatusCode = .Status
End With
WinHTTP_URLExist = (lStatusCode = 200)
Error_Handler_Exit:
On Error Resume Next
Set oWinHttp = Nothing
Exit Function
Error_Handler:
'-2147012889 The server name or address could not be resolved
'-2147012894 The operation timed out
If Err.Number <> -2147012889 And Err.Number <> -2147012894 Then
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Source: WinHTTP_URLExist" & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
End If
Resume Error_Handler_Exit
End Function