我建议使用“规则”的二维数组。当用户添加规则时,规则类型(等、不等)和要测试的参数等信息将被输入到数组中。最后,在进行检查时,您可以使用循环内的 if..then 语句中的参数来测试数组的所有元素。如果所有规则都与 AND 运算符组合,那么您可以将布尔变量设置为 false 并退出循环。如果您需要更多详细信息或代码示例,请发布一些我可以处理的试用代码。
使用代码编辑:
我制作了一个可以用于此目的的类:
Option Explicit
'Class Parameters
Dim pRules() As Variant 'note the variant data type
Dim pCountRules As Long
Private Sub class_initialize()
pCountRules = 0
End Sub
Public Sub AddRule(Parameter As Variant, Condition As Variant)
'note the variant data types
If TypeName(Parameter) <> TypeName(Condition) Then
'one possible exception I can think of, handle this here
Exit Sub
End If
If pCountRules = 0 Then
pCountRules = 1
ReDim pRules(1 To 2, 1 To 1)
pRules(1, 1) = Parameter
pRules(2, 1) = Condition
Else
pCountRules = pCountRules + 1
ReDim Preserve pRules(1 To 2, 1 To pCountRules)
pRules(1, pCountRules) = Parameter
pRules(2, pCountRules) = Condition
End If
End Sub
Public Sub ResetRules()
Erase pRules
pCountRules = 0
End Sub
Public Function CheckRules() As Boolean
Dim i As Integer
If pCountRules = 0 Then
CheckRules = True 'or false, depends on your logic
Else
CheckRules = True
For i = 1 To pCountRules
If pRules(1, i) <> pRules(2, i) Then
CheckRules = False
Exit For
End If
Next i
End If
End Function
Private Sub Class_Terminate()
Erase pRules
End Sub
注意变量数据类型的使用。我尽可能避免这种情况,您需要大量的异常处理。如果您的数据类型已确定,那么您可以更改它并包括正确的验证。我测试了这个类,如下所示:
Option Explicit
Sub test()
Dim Rules As clsRules
Dim testarr(1 To 1, 1 To 3) As String
Dim testparam(1 To 3) As String
testarr(1, 1) = "a"
testarr(1, 2) = "b"
testarr(1, 3) = "c"
testparam(1) = "a"
testparam(2) = "b"
testparam(3) = "c"
'values match
Set Rules = New clsRules
Rules.AddRule testarr(1, 1), testparam(1)
Rules.AddRule testarr(1, 2), testparam(2)
Rules.AddRule testarr(1, 3), testparam(3)
'will print true
Debug.Print Rules.CheckRules
'change parameter so values do not match
testparam(3) = "a"
Rules.ResetRules
Rules.AddRule testarr(1, 1), testparam(1)
Rules.AddRule testarr(1, 2), testparam(2)
Rules.AddRule testarr(1, 3), testparam(3)
'will print false
Debug.Print Rules.CheckRules
'clean up
Erase testarr
Erase testparam
Set Rules = Nothing
End Sub
我希望这对你有用。