编译错误:尝试对多个服务器执行ping操作的代码无效的外部过程

时间:2019-04-19 03:43:53

标签: excel vba

我尝试获得一个Excel工作表来按一下按钮ping多台服务器。

我按照指南中的所有步骤进行操作
https://wintelgeeks.com/2016/02/11/script-to-ping-multiple-servers-using-excel/
但得到一个

  

“编译错误:无效的外部过程”。

我在Windows 2012 R2服务器上使用Excel Office 365。

Sub PingSystem()
    ‘—-First clear the cells in Row B—————–
    ClearStatusCells
    ‘—————————————————
    Dim strcomputer As String
    Application.ScreenUpdating = True
    For introw = 2 To ActiveSheet.Cells(65536, 1).End(xlUp).Row
        strcomputer = ActiveSheet.Cells(introw, 1).Value
        ‘————Call ping function and post the output in the adjacent cell——-
        If Ping(strcomputer) = True Then
            strpingtest = “Online”
            ActiveSheet.Cells(introw, 2).Value = strpingtest
        Else
            ActiveSheet.Cells(introw, 2).Font.Color = RGB(200, 0, 0)
            ActiveSheet.Cells(introw, 2).Value = “Offline”
        End If
    Next
    MsgBox “Script Completed”
End Sub


Function Ping(strcomputer)
    Dim objshell, boolcode
    Set objshell = CreateObject(“wscript.shell”)
    boolcode = objshell.Run(“ping -n 1 -w 1000 ” & strcomputer, 0, True)
    If boolcode = 0 Then
        Ping = True
    Else
        Ping = False
    End If
End Function


Sub ClearStatusCells()
    Range(“B2:B1000”).Clear
End Sub

1 个答案:

答案 0 :(得分:0)

VBA中的注释标记为',但您的注释标记为:VBA编译器无法将字符识别为撇号,因此将其视为标识符的一部分。

从语法上讲,一个单独位于一行代码上的标识符必须是一个过程调用(或对某些全局作用域对象的不合格成员调用)。

并且过程调用(或成员调用)在模块的(declarations)部分或过程范围之外的任何地方都不合法,因为它是可执行语句。

然后,字符串定界符",这也使编译器感到困惑。

修复单引号和双引号,代码将编译。 Ctrl + H 查找并替换=)

经验法则,如果未将其格式化为代码,请不要从博客文章中复制并粘贴代码。

Public Sub PingSystem()
    Dim failed As Boolean
    On Error GoTo CleanFail
    'Application.ScreenUpdating = False

    Dim sheet As Worksheet
    Set sheet = ActiveSheet 'TODO set to a more specific sheet

    ClearStatusCells sheet

    Dim currentRow As Long
    For currentRow = 2 To sheet.Cells(sheet.Rows.Count, 1).End(xlUp).Row

        Dim host As Variant
        host = sheet.Cells(currentRow, 1).Value

        If Not IsError(host) Then

            Dim pingSuccess As Boolean
            pingSuccess = Ping(CStr(host))

            sheet.Cells(currentRow, 2).Value = IIf(pingSuccess, "Online", "Offline")
            sheet.Cells(currentRow, 2).Font.Color = IIf(pingSuccess, vbBlack, vbRed)

        End If

    Next
CleanExit:
    Application.ScreenUpdating = True
    If failed Then
        MsgBox "Script completed unexpectedly.", vbExclamation
    Else
        MsgBox "Script completed.", vbInformation
    End If
    Exit Sub
CleanFail:
    failed = True
    Resume CleanExit
End Sub

Private Function Ping(ByVal host As String) As Boolean
    With CreateObject("wscript.shell")
        Ping = .Run("ping -n 1 -w 1000 " & host, 0, True) = 0
    End With
End Function

Private Sub ClearStatusCells(ByVal sheet As Worksheet)
    sheet.Range("B2:B1000").Clear 'TODO use a named range?
End Sub