数据验证与VBA列表匹配

时间:2018-07-12 09:10:02

标签: excel vba excel-vba

我在excel中有一定范围的单元格,我想将数据验证应用于其他数据验证。

我希望用户只有3个单元格范围内的数据输入选项:

  1. 一个数字
  2. 数字范围或
  3. 从包含单词和数字的下拉列表中进行选择。

我已经通过以下功能实现了1号和2号:

Function checkStr(ByVal str As String) As String

    Dim objRegEx As Object, allMatches As Object
    Set objRegEx = CreateObject("VBScript.RegExp")

    With objRegEx
        .MultiLine = False
        .IgnoreCase = False
        .Global = True
        .Pattern = "^\d+(-\d+)?$"
    End With


    Set allMatches = objRegEx.Execute(str)
    checkStr = (allMatches.Count > 0)

End Function

由于上述功能仅允许输入数字或一定范围内的数字,因此关于如何添加验证以允许包含单词和数字的预定义列表中的值的任何想法?

2 个答案:

答案 0 :(得分:1)

列表从某个范围取值。因此,获取列表的范围并使用Application.Match()来检查str是否存在:

Public Function checkStr(str As String) As Boolean

    Dim isItError As Variant
    isItError = Application.Match(str, Worksheets(1).Range("A1:A5"), 0)

    checkStr = Not IsError(isItError)

End Function

Application.Match()将返回errortrue。因此,可以使用Not IsError()来固定您的功能。


如果您想将字符串与字符串和数字作为数字进行比较,请尝试将变量作为Variant传递,并让VBA决定其实际含义:

Public Function checkMe(someVar As Variant) As Boolean

    Dim isItError As Variant
    Dim formulaAddress As String

    With Range("C1").Validation
        formulaAddress = Right(.Formula1, Len(.Formula1) - 1)
    End With

    isItError = Application.Match(someVar, Range(formulaAddress))
    checkMe = Not IsError(isItError)

End Function

如果您将变量明确定义为数字或字符串,则Application.Match()比较中将排除另一个选项:

?Application.Match("1",Array(1,2,3))
Error 2042
?Application.Match(1,Array(1,2,3))
1 
?Application.Match("1",Array("1","2","3"))
1 
?Application.Match(1,Array("1","2","3"))
Error 2042

答案 1 :(得分:1)

我建议更改返回值As Boolean,然后仅对有效列表条目数组过滤str

Function checkStr(ByVal str As String) As Boolean

    Dim objRegEx As Object, allMatches As Object
    Set objRegEx = CreateObject("VBScript.RegExp")

    With objRegEx
        .MultiLine = False
        .IgnoreCase = False
        .Global = True
        .Pattern = "^\d+(-\d+)?$"
    End With

    Set allMatches = objRegEx.Execute(str)


    Dim ValidList As Variant
    ValidList = Array("123", "456") 'your list of valid entries

    'check if either str is in the ValidList OR matches the regex
    If (UBound(Filter(ValidList, str)) > -1) Or (allMatches.Count > 0) Then
        checkStr = True
    End If

End Function

如果有效条目列表在范围内,则可以将其替换为:

ValidList = WorksheetFunction.Transpose(Worksheets("SheetName").Range("A1:A10").Value)