我正在尝试根据ping的结果更改对象的颜色。我正在ping的每个设备都有一个对象,对象名称与计算机相同。所以我试图用一个可以用For语句传递throw的varible替换对象名。
Private Sub PING_Click()
Dim strCommand As String
Dim strPing As String
Dim myIP() As String
ReDim myIP(0 To 3) As String
myIP(0) = "computer1"
myIP(1) = "computer2"
myIP(2) = "computer3"
myIP(3) = "computer4"
For i = 0 To 3
MsgBox myIP(i)
strCommand = "%ComSpec% /C %SystemRoot%\system32\ping.exe -n 1 -w 500 " & myIP(i) & " | " & "%SystemRoot%\system32\find.exe /i " & Chr(34) & "TTL=" & Chr(34)
strPing = fShellRun(strCommand)
objcol = myIP(i) & ".ForegroundColor"
If strPing = "" Then
objcol = 255
Else
objcol = 65280
End If
Next i
End
End Sub
我的问题在
objcol = myIP(i) & ".ForegroundColor"
If strPing = "" Then
objcol = 255
Else
objcol = 65280
由于某种原因,它不会改变对象的颜色。它做得很好,如果我硬编码,变量例如
objcol = myIP(i) & ".ForegroundColor"
If strPing = "" Then
computer1.ForegroundColor = 255
Else
computer1.ForegroundColor = 65280
非常感谢任何帮助。
由于
答案 0 :(得分:3)
你在混淆这句话:
computer1.foregroundcolor
其中" Computer1"表示一个对象,其前景色可以改变:
objcol
这是一个字符串,其值为" computer1.foregroundcolor"。
为了做到这一点,你需要创建一个对象数组,如下所示:
Dim myIP() As Object
ReDim myIP(0 To 3) As Object
myIP(0) = computer1
myIP(1) = computer2
myIP(2) = computer3
myIP(3) = computer4
For i = 0 To 3
MsgBox myIP(i)
strCommand = "%ComSpec% /C %SystemRoot%\system32\ping.exe -n 1 -w 500 " & myIP(i).name & " | " & "%SystemRoot%\system32\find.exe /i " & Chr(34) & "TTL=" & Chr(34)
strPing = fShellRun(strCommand)
If strPing = "" Then
myIP(i).foregroundcolor = 255
Else
myIP(i).foregroundcolor = 65280
End If
Next i
End
End Sub
这假设您将computer1,computer2作为对象放入阵列,并且这些对象具有" .name"包含名称" computer1"," computer2"等
答案 1 :(得分:2)
String
不是对象引用;你根本无法做到这一点。
作为already mentioned,您所做的就是重新分配字符串'值:
objcol = myIP(i) & ".ForegroundColor" ' objcol is "[computername].ForegroundColor"
...
objcol = 255 ' objcol is now "255"
您可以将Scripting.Dictionary
作为键[computername]
,将实际对象作为值引用,然后执行以下操作:
Dim mappings As New Scripting.Dictionary
mappings.Add "computer1", computer1
mappings.Add "computer2", computer2
...
mappings(myIP(i)).ForegroundColor = IIf(strPing = vbNullString, 255, 65280)