所以我设置了一个自定义功能区,它有两个按钮:一个用于运行模拟,另一个用于取消模拟。模拟宏运行时,会显示一个进度条,直到它完成。
取消按钮会运行一个只有End
的子组件。但问题是,当用户点击取消时,会出现一个错误,表示"应用程序定义或对象定义错误"
基本上我试图在功能区中找到一个按钮来停止模拟宏而不会抛出错误。
我尝试使用On Error
语句转到子结尾,但它仍然是相同的。这是宏的代码:
Public Sub SimCallback(control As IRibbonControl)
Dim CurrentTrial As Long
Dim NumberOfTrials As Long
Dim StartTime As Double
Dim EndTime As Double
Dim SimBar As ProgressBar
Set SimBar = New ProgressBar
' Custom parameters for progress bar. References separate class
With SimBar
.Title = "Simulation Progress"
.StartColour = rgbGreen
.Top = Application.Top + 125
.Left = Application.Left + 25
End With
' Pre-sim actions
Worksheets("Histograms").EnableCalculation = False
Worksheets("Monte Carlo Results").EnableCalculation = False
StartTime = Timer
Worksheets("Monte Carlo Calculation").Range("U1:V10000").Clear
Let CurrentTrial = 1
NumberOfTrials = Worksheets("Monte Carlo Results").Range("M2").value
SimBar.TotalActions = NumberOfTrials
SimBar.ShowBar
' Loop repeats until selected number of trials have been performed.
' Values are stored in U and V columns on same sheet.
Do While CurrentTrial < NumberOfTrials
DoEvents
Worksheets("Monte Carlo Calculation").Calculate
For CurrentTrial = 1 To NumberOfTrials
Worksheets("Monte Carlo Calculation").Range("U" & CurrentTrial).value = Worksheets("Monte Carlo Calculation").Range("J2").value
Worksheets("Monte Carlo Calculation").Range("V" & CurrentTrial).value = Worksheets("Monte Carlo Calculation").Range("T2").value
SimBar.NextAction
Next CurrentTrial
CurrentTrial = CurrentTrial + 1
Loop
' Output range is copied to separate sheet, since referencing the original sheet slowed down the simulation time.
Worksheets("Monte Carlo Calculation").Range("U1:V10000").Copy Destination:=Worksheets("Histograms").Range("H1:J10000")
Worksheets("Histograms").EnableCalculation = True
Worksheets("Monte Carlo Results").EnableCalculation = True
' Display sim time and terminate progress bar
EndTime = Round(Timer - StartTime, 2)
SimBar.Terminate
MsgBox "Simulation Complete (" & EndTime & " seconds)", vbInformation
End Sub
答案 0 :(得分:0)
可能性如下:
1)创建一个名为eg的公共变量Running
:
Public Running As Boolean
在任何程序之外的标准代码模块中声明。
2)在SimCallback
的代码中,有一行
Running = True
代码顶部并替换
Do While CurrentTrial < NumberOfTrials
通过
Do While Running And CurrentTrial < NumberOfTrials
3)在取消按钮的代码中,将End
替换为
Running = False
这将允许清理行SimBar.Terminate
执行。