excel vba ping 计算机列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24442936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
excel vba ping list of computers
提问by Divin3
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
我正在做一个项目。我的目标是,从 excel 列表中 ping 所有计算机,但无法弄清楚为什么它不起作用。我对这种编程语言很陌生,我确信我错过了一些东西,因为我收到错误消息:需要对象
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".
如果我写 sPing(""),我可以获得结果,但我希望它获得列表中的 pc-s 的名称。这只是脚本的测试版本,我现在正在用一台电脑测试它,这就是我使用“MsgBox”的原因。
Thank you
谢谢
回答by Shiva
The 2nd line inside the Sub pingall_Click()
subroutine is the one throwing the Object Required
error. i.e. the following line.
Sub pingall_Click()
子程序中的第二行是抛出Object Required
错误的那一行。即以下行。
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.
此外,您不应该将函数的返回值分配sPing
回c
. 因为这样做会覆盖您在单元格中的服务器/IP 地址的名称,因为 forloop 使用c
变量一次循环 1 个单元格。
So instead, assign it back to a new string variable, and then do whatever you want with it.
因此,相反,将它分配回一个新的字符串变量,然后对它做任何你想做的事情。