0
因此,我設置了一個自定義功能區,其中有兩個按鈕:一個用於運行模擬,另一個用於取消它。當模擬宏運行時,會出現一個進度條,直到完成。VBA應用程序或對象定義的錯誤結尾時
取消按鈕運行一個只有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
看到這裏:https://stackoverflow.com/questions/3979893/how-to-stop-vba-code-running –