2013-05-03 202 views
1

我有一个在电子表格中被调用超过1000次的函数(从数据库查找价格)偶尔会在数据库不可用的环境中打开电子表格。当发生这种情况时,我有错误代码来处理它,这会推送一个消息框。强制Excel在功能错误后停止计算

我想要一种方法来停止Excel计算,如果第一个失败,所以事情可以修复。我会弹出一个消息框,提供停止计算的选项。

有没有办法做到这一点?截至目前,它基本上弹出消息框1000次,并且很多时间Ctrl + 中断(某些键盘甚至没有中断键)或Esc不会停止运行,因为它太快了以获得突破...

ErrorHandler: 
' clean up 
If Not rst1 Is Nothing Then 
    If rst1.State = adStateOpen Then rst1.Close 
End If 
Set rst1 = Nothing 

If Not Con1 Is Nothing Then 
    If Con1.State = adStateOpen Then Con1.Close 
End If 
Set Con1 = Nothing 

If Err <> 0 Then 
    MsgBox Err.Source & "-->" & Err.Description, , "Error" 
End If 


End Function 

回答

0

您可以使用标签并使用转到标签使用goto。见下面的代码。

On Error GoTo ErrorHandler 


a = 1/0 

ErrorHandler: 
' clean up 
If Not rst1 Is Nothing Then 
    If rst1.State = adStateOpen Then rst1.Close 
End If 
Set rst1 = Nothing 

If Not Con1 Is Nothing Then 
    If Con1.State = adStateOpen Then Con1.Close 
End If 
Set Con1 = Nothing 

If Err <> 0 Then 
    MsgBox Err.Source & "-->" & Err.Description, , "Error" 
    GoTo exit_func 
End If 

exit_func: 

End Function 
+0

这不会做任何事来阻止Excel中的计算......并且除了列出的代码之外确实没有做任何其他事情。退出该功能不会停止宏或停止计算。 – OneTallShort 2013-05-03 01:34:11

+0

@OneTallShort它还会弹出消息框1000次吗? – Santosh 2013-05-03 01:37:40

+0

当然,因为该函数被称为从电子表格1000次...不循环1000次..这被定义为一个函数,而不是一个宏子程序。它叫做= GetPrice(A1,C1,D1),所以当excel计算时,它试图更新电子表格中每个函数的实例。 – OneTallShort 2013-05-03 02:19:13

0

我想你可以通过设置功能为布尔解决这个问题,我尝试使用下面的例子给大家讲解:

Sub plus() 

Dim cond As Boolean 
Dim a As Integer 

cond = True 'initialize the condition 

Dim rowA As Long 
rowA = Range("A" & Rows.Count).End(xlUp).Row 

For a = 1 To 3 'calling to loop to call function 
    If cond = True Then 
     cond = plusnumber(cond, rowA) ' passing the data to function 
    Else 
     Exit Sub 
    End If 
Next 

End Sub 

以下是这是布尔类型的函数我刚才提到:

Function plusnumber(condition, rowA) As Boolean 

Dim i As Integer 

For i = 2 To rowA 
    If Range("A" & i).Value > 5 Then 
     MsgBox "the number greater than 5)" 
     plusnumber = False 'set the condition as false and exit function 
     Exit Function 
    Else 
     Range("B" & i).Value = Range("B" & i).Value + Range("A" & i).Value 
    End If 
Next 


End Function 

希望它能帮助你。