excel vba ping list of computers

不问归期 提交于 2019-12-12 14:12:52

问题


I am working on a project. My goal is, to ping all of the computers from an excel list, but can't figure out why it isn't working. I am quite new at this programming language, and I am sure that I miss out something, because I get the error message: Object required

so here is my code

the main:

Sub pingall_Click()
Dim c As Range
c = Target.Name

For Each c In Range("A1:N50")
    If (Left(c, 1) = "C" Or Left(c, 1) = "T") And IsNumeric(Right(c, 6)) And Len(c) = 7 Then
    c = sPing(c)
        If c = "timeout" Then
            MsgBox "timeout"
        ElseIf c < 16 And c > -1 Then
            MsgBox "ok"
        ElseIf c > 15 And c < 51 Then
            MsgBox "not ok"
        ElseIf c > 50 And c < 4000 Then
            MsgBox "big delay"
        Else
            MsgBox "error"

        End If
    End If
Next c
End Sub

The function:

Public Function sPing(sHost) As String

Dim oPing As Object, oRetStatus As Object

Set oPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
  ("select * from Win32_PingStatus where address = '" & sHost & "'")

For Each oRetStatus In oPing
    If IsNull(oRetStatus.StatusCode) Or oRetStatus.StatusCode <> 0 Then
        sPing = "timeout" 'oRetStatus.StatusCode
    Else
        sPing = sPing & vbTab & oRetStatus.ResponseTime & Chr(10)
    End If
Next
End Function

I can get the result if I write sPing(""), but I want it to get the name of pc-s that are in the list. This is just a test version of the script, I am testing it with one pc for now, that is why I use "MsgBox".

Thank you


回答1:


The 2nd line inside the Sub pingall_Click() subroutine is the one throwing the Object Required error. i.e. the following line.

c = Target.Name

If you comment it out or delete it, it works. (I tried it.)

Also, you should not be assigning the return value from the function sPing back to c. Because doing so will overwrite the name of the Server / IP address you have in the cell, since the forloop is looping over 1 cell at a time using the c variable.

So instead, assign it back to a new string variable, and then do whatever you want with it.



来源:https://stackoverflow.com/questions/24442936/excel-vba-ping-list-of-computers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!