尽管我的问题原理同样适用于Excel或Word VBA,但我正在MS Access中编写一些VBA。我写了一个函数GetStringParameterFromTable,它返回一个字符串值。尽管尽我最大的努力编写了该函数,但该函数可能会导致VBA生成错误。如果发生错误,我不希望代码崩溃,因此必须使用错误处理。但是,我不希望代码显示错误消息并在出现错误时在函数内停止。我希望函数完成执行并将控制权返回给调用过程,然后让调用过程显示错误消息并进行整理,例如关闭打开的文件。我的问题是:调用过程如何知道所调用的函数中存在错误,以及如何获取错误消息?
我已经想到了三种实现方法:
(1)将GetStringParameterFromTable变成一个Sub,然后将其ParameterValue,ErrorFlag和ErrorMessage传递给引用。
(2)保持GetStringParameterFromTable为函数,将ErrorFlag和ErrorMessage定义为全局变量,并使该函数更改ErrorFlag和ErrorMessage。
(3)保持GetStringParameterFromTable为函数,并定义具有三个组件的类型-ParameterValue,ErrorFlag和ErrorMessage-并使GetStringParameterFromTable返回我定义的类型的值。
我认为我的要求必须很普遍,但是我找不到有关其实现方式的任何示例。是否有人对我的建议是最好的方法有任何看法,或者是否有我没有想到的更好的方法?
答案 0 :(得分:1)
自C#.net实现元组以来,我一直在考虑同一件事。我已经使用VBA的type
实现了元组来创建我的元组。我所做的是:
Public Type myTuple
Value as String 'Or whatever type your value needs to be
ErrCode as Long
ErrDesc as String
End Type
Public Function DoWork (ByRef mObject as MyClass) as myTuple
Dim retVal as myTuple
'Do whatever work
If Err.Number <> 0 then
retVal.Value = Nothing
retVal.ErrNumber = Err.Number
retVal.ErrDesc = Err.Description
Else
Set retVal.Value = Whatever Makes Sense
retVal.ErrNumber = 0
retVal.ErrDesc = VbNullString
End If
DoWork = retVal
End Function
我想更具体一点,但是您没有提供代码示例。
答案 1 :(得分:1)
我正在这样做,并将错误记录在表中:
' Lookups Replacements
'---------------------
Function DLook(Expression As String, Domain As String, Optional Criteria) As Variant
On Error GoTo Err_Handler
Dim strSQL As String
strSQL = "SELECT " & Expression & " FROM " & Domain 'DLookup
'DCount: strSQL = "SELECT COUNT(" & Expression & ") FROM " & Domain
'DMax: strSQL = "SELECT MAX(" & Expression & ") FROM " & Domain
'DMin: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DFirst: strSQL = "SELECT FIRST(" & Expression & ") FROM " & Domain
'DLast: strSQL = "SELECT LAST(" & Expression & ") FROM " & Domain
'DSum: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DAvg: strSQL = "SELECT AVG(" & Expression & ") FROM " & Domain
If Not IsMissing(Criteria) Then strSQL = strSQL & " WHERE " & Criteria
DLook = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenForwardOnly)(0)
Exit Function
Err_Handler:
'Can be made as Error Sub as well
Dim ErrNumber as Integer
Dim ErrDescription as String
ErrNumber = Err.Number
ErrDescription = Err.Description
Err.Clear
On Error Resume Next
Dim strSQL as String
strSQL = "INSERT INTO tblErrorLog (ErrorNumber, ErrorDescription) VALUES (" & ErrNumber & ", '" & ErrDescription & "')"
Currentdb.Excecute strSQL, dbFailOnError
End Function
致电:
If DLook("Column2", "Table1", "Column1 = " & ID) = 0 Then
'Do stuff
End If
If DLook("Column2", "Table1") = 0 Then
'Do other stuff
End If