Excel VBA – 一段时间后删除文本

我正在尝试在单元格中显示一些提示,如下所示。

Dim text As String text = "Hello World" If Range("A1") = 1 Then Range("B1") = text Application.Wait (Now + TimeValue("0:00:05")) Range("B1") = "" End If 

如果vba只有上面的代码,代码运行完美,但对于我的情况来说,在这个“提示”函数之前有一大块代码。 每当IF语句变为TRUE时,我的鼠标光标就会变成窗口的加载符号,而单元格B1不显示任何内容。

在5秒之后,“Hello World”会在B1单元再次变空之前很短暂地出现,就像它打算做的那样,但是时间全都搞砸了。

我知道这里的硬件可能有问题,但还有其他方法可以解决吗?

在没有看到上面的代码的情况下诊断你的具体问题是很困难的,但是你可以尝试一下:

 Sub Test() Dim text As String, iLoop As Integer text = "Hello World" If Range("A1") = 1 Then For iLoop = 1 To 5 '5 is the number of seconds to wait Range("B1") = text DoEvents Application.Wait (Now + TimeValue("0:00:01")) Loop Range("B1") = "" End If End Sub 

一个可能的解决scheme是处理事件 – 在工作表中,像这样:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Intersect(Target, Range("A1")) Is Nothing Then Exit Sub If Range("A1") = 1 Then Range("B1") = "Hello world" Application.Wait (Now + TimeValue("0:00:05")) Range("B1") = vbNullString End If End Sub 

确保你有Application.EnableEvents = True ,在oder看到不同之处。

当Application.Wait将CPU耗尽到100%(“ 忙等待 ”)时,最好使用Windows Sleep

您必须在代码的顶部放置一个声明:

 Private Declare Sub Sleep Lib "kernel32" (ByVal lngMilliSeconds As Long) 

然后,写一个简单的Sub这样的:

 Public Sub WaitSeconds(seconds As Integer) Dim WaitUntil As Date WaitUntil = DateAdd("s", seconds, Now) Do While Now < WaitUntil Sleep 100 DoEvents Loop End Sub