【问题标题】:Screen not updated after N iterationsN 次迭代后屏幕未更新
【发布时间】:2015-09-01 10:32:03
【问题描述】:

我在我的 excel 上运行了一个非常简单的类似“Snake”的游戏,这意味着我需要在我的 main-while 循环内不断更新屏幕。 “蛇”(基本上是彩色单元格)在 20x20 的桌子内随机移动。

它可以运行几秒钟,但是,在某些点屏幕停止更新; ans excel 停止响应,同时仍在运行代码。这会导致崩溃。

我用 For 循环替换了 while 循环,这样可以避免崩溃,但屏幕仍然会停止更新,直到循环结束。当循环停止时,屏幕会最后一次更新。 我还在每个函数之后包含了“睡眠”语句,但是,这并没有帮助。 以下是主要代码:

    Sub main()
    Dim table(20, 20) As Integer
    Dim index_move As Integer
    'Position class contains only X and Y parameters
    Dim index_actual_head_pos As Position 
    Set index_actual_head_pos = New Position

    Dim i As Long
    index_actual_head_pos.x = 5
    index_actual_head_pos.y = 15
    Application.ScreenUpdating = True

    For i = 1 To 50 'this remplaces the initial while loop
    'next line generates a random movement, bounded by a 20x20 matrix
    index_move = generer_movement(index_actual_head_pos)
    'next line updates the "snake" position params
    Call update_position(index_actual_head_pos, index_move)
    'next line deletes previous snake and draws a new one
    Call draw(index_actual_head_pos)
    Sleep (200)
    Next i
    End Sub

请注意,问题实际上是屏幕更新。如前所述,我不知道如何强制excel不断更新屏幕

非常感谢,

丹尼斯

【问题讨论】:

    标签: vba excel while-loop crash


    【解决方案1】:

    您可能应该放弃 Sleep(200) 并让 Excel 应用程序对象在 200 毫秒内进行一些处理。

    dim dTill as double   'should be at the top with the other var declarations
    
    dtill = Timer + 0.200
    do while timer < dTill and timer > 0.200: DoEvents: loop
    

    timer &gt; 0.200 很重要,因为计时器会在午夜重置,如果您在 1/₅ 秒内越过午夜,您不希望它让一切停止 24 小时。

    【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2016-04-09
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多