2017-06-13 64 views
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 
+1

看到這裏:https://stackoverflow.com/questions/3979893/how-to-stop-vba-code-running –

回答

0

可能性如下:

1)創建例如稱爲公共變量Running

Public Running As Boolean 

在一個標準的代碼模塊的任何過程的外部聲明。

2)在用於SimCallback的代碼,具有線

Running = True 

朝向代碼的頂部,並通過

Do While Running And CurrentTrial < NumberOfTrials 

3取代

Do While CurrentTrial < NumberOfTrials 

)在代碼對於取消按鈕,請將End替換爲

Running = False 

這將允許清理行SimBar.Terminate執行。

相關問題