VBA 用户窗体是 "Not Responding" 而宏是 运行

VBA userform is "Not Responding" while macro is running

为什么当我 运行 以下代码时我的用户表单显示 "Not Responding"?我一直试图解决它,但它还没有解决。

实际上它有时会起作用。我认为问题与屏幕更新有关。

' The input button in Sheet1
Sub Rectangle1_Click()

    'Remember time when macro starts
    StartTime = Timer

    ' To improve speed and performance
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    ' Show the userform
    UserForm1.Show vbModeless
    UserForm1.Label1.Caption = "Calculation in progress ... " & vbNewLine & "Please be patient"
    UserForm1.Label1.Font.Size = 12
    UserForm1.Top = (Application.Height / 2) - (UserForm1.Height / 2)
    UserForm1.Left = (Application.Width / 2) - (UserForm1.Width / 2)
    UserForm1.CommandButton1.Visible = False
    UserForm1.Repaint

    Call Insert_RawData

    'Determine how many seconds code took to run
    SecondsElapsed = Round(Timer - StartTime, 2)
    UserForm1.Label1.Caption = "This code ran successfully in " & SecondsElapsed & " seconds"
    UserForm1.CommandButton1.Visible = True

    ' Return back to the original settings
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationSemiautomatic

End Sub

可能有很多事情。如果问题像您提到的那样是间歇性的,那么很可能该程序正在运行,并且 Windows 只是将其标记为无响应,因为该程序正在努力响应 OS.

可能的问题可能是以下一项或多项:

  • Insert_RawData
  • 正在处理的数据量
  • 宏 运行ning
  • 时打开的工作簿中的数据量
  • Insert_RawData 遇到错误,因为它使用的其中一个单元格中有 bad/unhandled 值(不太可能)

尝试缩小来源范围的一些建议:

  • 如果有一种方法可以始终如一地 运行 以便您在 Excel window 中获得 "Non-Responsive",请在 [=10] 的调用处插入一个断点=] 并观察它 运行 看看它是否遇到错误
    • 或者,尝试将一些错误检查放入 Insert_RawData 并在处理错误检查失败的情况的代码上设置断点
  • 捕获在宏的每个 运行 期间处理的数据量(字节、单元格,无论最简单的是什么)以及 运行 时间,看看是否有你的命中阈值(例如。 <= 1 GB 运行 没问题,但 >1GB 并且应用程序看起来冻结)

不过,除非您在 Insert_RawData 中遇到错误,否则宏很可能会完成,只是可能需要很长时间。