VBA: Reduce time to check if network drive is available

65 views Asked by At

I have the following code to check if the network drive 192.168.50.175 is available to my computer.

Public Sub check_if_drive_exists()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Debug.Print "---"
    Debug.Print fso.driveExists("\\192.168.50.175\MyFolder")
End Sub

If the drive is available, I instantly get "True" on VBA immediate window. But if it is not, I have to wait sometimes over 30 seconds to obtain "False".

So my question is: Is there any way to reduce that time? I cannot understand why driveExists method takes so much time to give the "False" result. Actually that time is quite variable, but always long (i.e. several seconds).

Secondary, I noticed that if I write only the drive IPv4 address alone "\192.168.50.175" the method fails, but if I add the root folder "\192.168.50.175\MyFolder" it works fine. Why? After all the method is checking if the drive exists, not the folder!

Many thanks for the attention

1

There are 1 answers

2
FaneDuru On

Please, try the next way of checking if a computer is online. If you check for the drive, this one must be shared to be accessible... Using Ping, you know that the computer is online and you can access its shared folders:

Function GetPingRes(strIP As String) As Boolean
   Dim objPing As Object

   Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}"). _
       ExecQuery("Select * from Win32_PingStatus Where Address = '" & strIP & "'")

   If objPing.ItemIndex(0).StatusCode = 0 Then GetPingRes = True

   Set objPing = Nothing
End Function

It can be tested as:

Sub TestGetPingRes()
    Debug.Print GetPingRes("192.168.50.175") 'it returns instantly
    Debug.Print GetPingRes("192.168.50.176") 'it returns after about 4 seconds...
End Sub