Excel VBA: Screen doesn't refresh during loop

*爱你&永不变心* 提交于 2021-01-28 00:11:39

问题


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 here but 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 here if you want to try it.

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.


回答1:


The DoEvents must have time to do events ;-). So it is totally useless if you call it once after a sleep. It must work during the pause.

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.



来源:https://stackoverflow.com/questions/40015962/excel-vba-screen-doesnt-refresh-during-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!