VBA – Check if resource or url exists in the internet

If you are one of the many VBA developers, then most probably you have been asked once or twice to download some file from a local eshare or site. Before downloading it, it really makes sense to check, whether this resouce actually exists.

Obviously the first one exists and the second one does not exist.

The code below takes its status and if it is 200 OK, returns True.

Public Function CheckUrlExists(url) As Boolean
        
    On Error GoTo CheckUrlExists_Error
    
    Dim xmlhttp As Object
    Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
 
    xmlhttp.Open "HEAD", url, False
    xmlhttp.send
    
    If xmlhttp.Status = 200 Then
        CheckUrlExists = True
    Else
        CheckUrlExists = False
    End If
    
    Exit Function
    
CheckUrlExists_Error:
    CheckUrlExists = False
    
End Function

That’s all! It is late binding, so you even do not need to add an additional library to the probject.

Enjoy it!