了解shell函数的返回值

时间:2016-11-07 21:55:26

标签: excel vba excel-vba shell

我希望自动化一个过程,在这个过程中,我可以浏览设备列表,ping它们,并了解它们是否已启动(意味着它们正在通信)或关闭(没有成功ping)。我查看了一些教程和计划,并将其发布到以下脚本中。

我可能会对shell函数和我下面的函数感到困惑。我理解为在我的ret值返回0时,ping是失败的。但是,我认为我错了。任何人都可以向我提供有关此函数问题以及如何使用返回值的清晰度。更好的是,有没有人试图创造类似于我正在做的事情?

Sub testPing()

    Dim WshShell
    Set WshShell = VBA.CreateObject("WScript.Shell")

    Dim testIP As String
    Dim testPort As String

    Dim yes, no As String
    yes = "true"
    no = "false"

    testIP = Cells(3, 2).Value
    testPort = Cells(3, 3).Value

    ret = WshShell.Run("C:\Users\John.Doe\paping.exe " & testIP & " -p " & testPort & " -c 3", 0, True)

    Debug.Print ret

End Sub

1 个答案:

答案 0 :(得分:2)

代码改编自This Question

使用此功能

Function GetPingResult(Host)
   Dim objPing As Object
   Dim objStatus As Object
   Dim Result As String

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

   For Each objStatus In objPing
      Select Case objStatus.StatusCode
         Case 0: strResult = "Connected"
         Case 11001: strResult = "Buffer too small"
         Case 11002: strResult = "Destination net unreachable"
         Case 11003: strResult = "Destination host unreachable"
         Case 11004: strResult = "Destination protocol unreachable"
         Case 11005: strResult = "Destination port unreachable"
         Case 11006: strResult = "No resources"
         Case 11007: strResult = "Bad option"
         Case 11008: strResult = "Hardware error"
         Case 11009: strResult = "Packet too big"
         Case 11010: strResult = "Request timed out"
         Case 11011: strResult = "Bad request"
         Case 11012: strResult = "Bad route"
         Case 11013: strResult = "Time-To-Live (TTL) expired transit"
         Case 11014: strResult = "Time-To-Live (TTL) expired reassembly"
         Case 11015: strResult = "Parameter problem"
         Case 11016: strResult = "Source quench"
         Case 11017: strResult = "Option too big"
         Case 11018: strResult = "Bad destination"
         Case 11032: strResult = "Negotiating IPSEC"
         Case 11050: strResult = "General failure"
         Case Else: strResult = "Unknown host"
      End Select
      GetPingResult = strResult
   Next

   Set objPing = Nothing
End Function

循环通过IP地址范围并将结果放在相邻的单元格中,如下所示:

Sub GetIPStatus()
  Dim cell As Range

  For Each cell In Worksheets("Sheet1").Range("A1:A5")
    Result = GetPingResult(cell.Value)
    cell.Offset(0, 1).Value = Result
  Next cell
End Sub

结果

enter image description here