【问题标题】:VBA Checking a textbox value against multiple conditionsVBA 根据多个条件检查文本框值
【发布时间】:2016-04-18 20:23:32
【问题描述】:

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

用户应该输入产品 ID,并且该 ID 可以是 5 种格式之一,并且根据该格式具有特定的长度。 5 个中有四个是字母数字 (10),第五个是数字 (13)。对于其中的三个(类型 A),我让它检查字符串的前几个字符,看看它们在前两个是公平游戏之后是否匹配。对于 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

非常感谢任何帮助!

【问题讨论】:

    标签: vba multiple-conditions


    【解决方案1】:

    我可能会使用如下函数:

    ...
    
        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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多