Excel VBA:循环期间屏幕不刷新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40015962/
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: Screen doesn't refresh during loop
提问by Lucas
I'm trying to make an image disappear and reappear while a loop is taking place. The code works as intended when I step through it, but when I run it the screen doesn't update until the loop is finished.
我正在尝试使图像在循环发生时消失并重新出现。代码在我逐步执行时按预期工作,但是当我运行它时,屏幕在循环完成之前不会更新。
I've tried adding things like DoEvents and ActiveWindow.SmallScroll as found herebut nothing seems to work. I have a feeling this problem may have something to do with my PC/settings/version of Excel and that the loop may work on some peoples' machines. I've uploaded a sample file hereif you want to try it.
我尝试添加的东西一样的DoEvents和ActiveWindow.SmallScroll如发现这里但似乎没有任何工作。我有一种感觉,这个问题可能与我的 PC/设置/Excel 版本有关,并且该循环可能适用于某些人的机器。如果您想尝试,我已经在此处上传了示例文件。
My Code is:
我的代码是:
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub ToggleImage()
For i = 1 To 20
Application.ScreenUpdating = True
ActiveSheet.Shapes("Picture 1").Visible = False
ActiveSheet.Shapes("Picture 2").Visible = True
ActiveSheet.Shapes("Picture 1").Visible = True
ActiveSheet.Shapes("Picture 2").Visible = False
Sleep 50
Next
End Sub
Sample workbook is attached.
附上示例工作簿。
采纳答案by Axel Richter
The DoEvents
must have time to do events ;-). So it is totally useless if you call it once after a sleep. It must work duringthe pause.
在DoEvents
必须有时间做活动;-)。所以如果你在睡眠后调用一次它是完全没用的。它必须在暂停期间工作。
The following should work:
以下应该工作:
Sub ToggleImage()
Dim dTime As Double
For i = 1 To 20
'ActiveSheet.Range("a1").Value = i
ActiveSheet.Shapes("Picture 1").Visible = False
ActiveSheet.Shapes("Picture 2").Visible = True
dTime = Time
Do While Time < dTime + 1 / 24 / 60 / 60 / 2
DoEvents
Loop
ActiveSheet.Shapes("Picture 1").Visible = True
ActiveSheet.Shapes("Picture 2").Visible = False
dTime = Time
Do While Time < dTime + 1 / 24 / 60 / 60 / 2
DoEvents
Loop
Next
End Sub
But you will not be able shortening the pause to 50 milli seconds. Even the refreshing the sheet will take more time.
但是您将无法将暂停缩短到 50 毫秒。即使刷新工作表也需要更多时间。