Excel/VBA - Abort script if network connection does not exist

前端 未结 3 973
無奈伤痛
無奈伤痛 2021-01-23 11:19

Are there any VBA code to look for a present internet connection?

I have a code that will run on a timer. This code will open a file on a local network share drive.

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-23 11:35

    This function works on both Mac and PC, with 32 as well as 64 bit Excel versions.

    Declaration:

    Option Explicit
    #If VBA7 And Win64 Then
        Private Declare PtrSafe Function InternetGetConnectedStateEx Lib "wininet.dll" (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Integer, ByVal dwReserved As Long) As Long
    #Else
        Private Declare Function InternetGetConnectedStateEx Lib "wininet.dll" (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Integer, ByVal dwReserved As Long) As Long
    #End If
    

    Function:

    Function IsInternetConnected() As Boolean
        Dim strConnType As String, lngReturnStatus As Long, MyScript As String
    
        If Application.OperatingSystem Like "*Macintosh*" Then
            MyScript = "repeat with i from 1 to 2" & vbNewLine
            MyScript = MyScript & "try" & vbNewLine
            MyScript = MyScript & "do shell script ""ping -o -t 2 www.apple.com""" & vbNewLine
            MyScript = MyScript & "set mystatus to 1" & vbNewLine
            MyScript = MyScript & "exit repeat" & vbNewLine
            MyScript = MyScript & "on error" & vbNewLine
            MyScript = MyScript & "If i = 2 Then set mystatus to 0" & vbNewLine
            MyScript = MyScript & "end try" & vbNewLine
            MyScript = MyScript & "end repeat" & vbNewLine
            MyScript = MyScript & "return mystatus"
            If MacScript(MyScript) Then IsInternetConnected = True
        Else
            lngReturnStatus = InternetGetConnectedStateEx(lngReturnStatus, strConnType, 254, 0)
            If lngReturnStatus = 1 Then IsInternetConnected = True
        End If
    End Function
    

    Using the function in a Sub:

    If IsInternetConnected Then
       MsgBox"Network Connection Detected"
    Else
       MsgBox"No Network Connection Detected"
    End If
    

提交回复
热议问题