Ms access 如何使用“重复”对检查进行编码;如果不取消,则“取消”;更优雅
在MS Access VBA中,我使用不同的参数以不同的方法进行不同的检查。一旦其中一个失败,Cancel设置为True,不应执行进一步的检查。看起来是这样的:Ms access 如何使用“重复”对检查进行编码;如果不取消,则“取消”;更优雅,ms-access,vba,coding-style,Ms Access,Vba,Coding Style,在MS Access VBA中,我使用不同的参数以不同的方法进行不同的检查。一旦其中一个失败,Cancel设置为True,不应执行进一步的检查。看起来是这样的: Cancel = checkMethodOne(param1) If Not Cancel Then Cancel = checkMethodTwo(param2, param3) End If If Not Cancel Then Cancel = checkMethodThree(param4) End If
Cancel = checkMethodOne(param1)
If Not Cancel Then
Cancel = checkMethodTwo(param2, param3)
End If
If Not Cancel Then
Cancel = checkMethodThree(param4)
End If
。。。等等有没有一种方法可以在不重复“If Not Cancel Then”子句的情况下更优雅地编写代码
类似于“whilenotcancel”的内容似乎是个问题,因为不同的方法具有不同的名称和参数。有什么想法吗?您可以使用
和
对多个语句求值,如果有返回false的语句,则返回false:
Cancel = checkMethodOne(param1) And checkMethodTwo(param2, param3) And checkMethodThree(param4)
如果这对你方便的话,可能要视情况而定。它比较短,代码也比较复杂,但可能会比较混乱
请注意,这会评估所有函数,因此如果它们是性能密集型的,则可能会运行更长的时间
或者,您可以尝试以下选择案例
,以避免执行所有比较:
Cancel = True
Select Case True
Case checkMethodOne(param1)
Case checkMethodTwo(param2, param3)
Case checkMethodThree(param4)
Case Else
Cancel = False
End Select
您只需使用
和
对多个语句求值,如果有返回false的语句,则返回false:
Cancel = checkMethodOne(param1) And checkMethodTwo(param2, param3) And checkMethodThree(param4)
如果这对你方便的话,可能要视情况而定。它比较短,代码也比较复杂,但可能会比较混乱
请注意,这会评估所有函数,因此如果它们是性能密集型的,则可能会运行更长的时间
或者,您可以尝试以下选择案例
,以避免执行所有比较:
Cancel = True
Select Case True
Case checkMethodOne(param1)
Case checkMethodTwo(param2, param3)
Case checkMethodThree(param4)
Case Else
Cancel = False
End Select
您还可以使用一个简单的If-ElseIf块: 备选方案:
Cancel = True
If checkMethodOne(param1) Then
ElseIf checkMethodTwo(param2, param3) Then
ElseIf checkMethodThree(param4) Then
Else
Cancel = False
End If
您还可以使用一个简单的If-ElseIf块: 备选方案:
Cancel = True
If checkMethodOne(param1) Then
ElseIf checkMethodTwo(param2, param3) Then
ElseIf checkMethodThree(param4) Then
Else
Cancel = False
End If
我个人的检查方法包括在检查失败时向用户显示一个消息框,因此这将导致在每个失败的检查中显示许多复选框。这不是我想要的。。。不幸的是VBA不支持,否则这对我来说是可行的。啊,我为那个案例提供了第二个解决方案哇,这是一个棘手的解决方案!我会用这个,它很紧凑。我只将“Select Case True”更改为“Select Case False”,因为checkMethods在出现错误时返回False。我的个别检查方法包括在检查失败时向用户显示一个消息框,因此这将导致每次失败的检查都会在每个复选框后面显示多个复选框。这不是我想要的。。。不幸的是VBA不支持,否则这对我来说是可行的。啊,我为那个案例提供了第二个解决方案哇,这是一个棘手的解决方案!我会用这个,它很紧凑。我只将“Select Case True”更改为“Select Case False”,因为checkMethods在出现错误时返回False。我已经比我问题中的代码更喜欢它了,但我更喜欢它,因为它更紧凑,没有重复“Cancel=True”。是的,Select Case很简洁。重复的代码是可以避免的,然后你会得到类似于Eric的代码-我不想只是重复。我已经比我问题中的代码更喜欢这个了,但我更喜欢它,因为它更紧凑,没有重复“Cancel=True”。是的,选择的案例很简洁。重复的代码是可以避免的,然后你会得到类似于Eric的代码——我不想重复。