VBA 根据多个条件检查文本框值

VBA Checking a textbox value against multiple conditions

我正在尝试针对 VBA 中的多个条件测试文本框的值,但不确定最好的方法。

用户应该输入一个产品 ID,该 ID 可以是 5 种格式之一,并且长度取决于该格式。 5 个中有四个是字母数字 (10),第五个仅是数字 (13)。对于其中的三个(类型 A),我让它检查字符串的前几个字符,看看它们是否匹配,因为在前 2 个是公平游戏之后。对于 B 型(仅限数字),我为该类型设置了一个数字范围,并试图强制使用 13 位数字长度。对于类型 C,它可以以 LMN 或 LMNZZ 开头,其余字符应该是数字。

这是我目前所知道的...

Dim ALen, Blen, Clen as Integer
Dim val_UpperLimit,val_LowerLimit as Double

val_UpperLimit = 9999999999999#
val_LowerLimit = 100000000000# (Only 12 digits b/c # can start with 0)
ALen = "10"
BLen = "13"
CLen = "14"

'Check for Product Type B (Should be numeric value only. 13 digits long)
If IsNumeric(txtProduct.Value) _
    And txtProduct.Value < val_UpperLimit _
    And txtProduct.Value > val_LowerLimit _
    And Len(txtProduct.Value) = BLen _

    'Check for Product Type A (Product will start with A0, D0 or YY and be 10 characters long)
    Or txtProduct.Value Like "A0*" _
        And Len(txtProduct.Value) = ALen _
    Or txtProduct.Value Like "D0*" _
        And Len(txtProduct.Value) = ALen _
    Or txtProduct.Value Like "YY*" _
        And Len(txtProduct.Value) = ALen _

    'Check for Product Type C (Product will start with LMN# or LMNZZ# and be a total of 14 characters/digits)
    Or txtProduct.Value Like "LMN*" _
    Or txtProduct.Value Like "LMNZZ*" _
        And Len(txtProduct.Value) = CLen _
Then
    txtProduct.Value = UCase(txtProduct.Value)
Else
    MsgBox "Please enter a valid Product ID", vbOKOnly
    txtProduct.SetFocus
    Exit Sub
End If

非常感谢任何帮助!

我可能会使用如下函数:

...

    If ProductIDIsValid(txtProduct.Value) Then
        txtProduct.Value = UCase(txtProduct.Value)
    Else
        MsgBox "Please enter a valid Product ID", vbOKOnly
        txtProduct.SetFocus
        Exit Sub
    End If

...

Public Function ProductIDIsValid(ByVal ProductID As String) As Boolean

    If Len(ProductID) = 10 And (Left(ProductID, 2) = "A0" Or Left(ProductID, 2) = "D0" Or Left(ProductID, 2) = "YY") Then 'Type A
        ProductIDIsValid = True
    ElseIf Len(ProductID) = 13 And Not ProductID Like "*[!0-9]*" Then 'Type B
        If CDbl(ProductID) >= 100000000000# Then ProductIDIsValid = True
    ElseIf Len(ProductID) = 14 And Left(ProductID, 3) = "LMN" Then 'Type C
        ProductIDIsValid = True
    Else 'No match
        ProductIDIsValid = False
    End If

End Function

所以您可以将该函数存储在模块中的某个地方,然后像我在代码中那样调用它。