Excel VBA使脚本asynchronous

我有一个脚本,可以ping通电脑列表,并根据得到的结果改变他们的背景颜色。

我的问题是,它在运行时会阻塞整个excel文件。

所以我的问题是,我怎样才能使它运行asynchronous?

这里是代码:

'ping 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 <- error code Else sPing = sPing & vbTab & oRetStatus.ResponseTime & Chr(10) End If Next End Function Sub pingall_Click() Dim c As Range Dim p As String Application.ScreenUpdating = True For Each c In ActiveSheet.Range("A1:N50") If Left(c, 7) = "172.21." Then p = sPing(c) If p = "timeout" Then c.Interior.ColorIndex = "3" ElseIf p < 16 And p > -1 Then c.Interior.ColorIndex = "4" ElseIf p > 15 And p < 51 Then c.Interior.ColorIndex = "6" ElseIf p > 50 And p < 4000 Then c.Interior.ColorIndex = "45" Else c.Interior.ColorIndex = "15" End If End If Next c Application.ScreenUpdating = False 

不幸的是,因为VBA运行在一个单独的线程中,所以不能做太多的事情。

但是,您可以通过放置来引入一定程度的响应

 VBA.DoEvents() 

在你的代码的各个地方,理想情况下在紧密的循环。 在你的情况下,把它们放在包含For的行之后。 这会暂停VBA并刷新将使Excel响应的事件队列。

(切换屏幕更新是一个坏主意,因为如果函数意外终止,可能会使事情处于不良状态,如果我是你,我会删除这些行。

Excel可以“asynchronous”计算。 调用sPing作为一个函数。

我不知道为什么你的范围是A1:N50。 我假设其中一列是IP地址,我将假设为A.因此,M列中的公式将看起来像=sPing(A1)

至于颜色编码,你可以使用条件格式。