2017-07-10 296 views
0

我在尝试查找单元格中的值是否与定义单元格下拉列表的命名范围中的值列表匹配。Excel VBA .find在不匹配时匹配

我的问题是,如果用户在单元格中输入星号,则此值不是有效的下拉值,但会验证列表中的第一项。在下面的代码中,如果szCellValue =“*”,那么验证不起作用。

有谁知道如何让这个搜索工作?

范围值

DESK

现场

N/A

代码来确定比赛

Dim bError As Boolean 

Dim oCell As Range 
Dim oFoundCell As Range 

Dim szCellValue As String 
Dim szLookupValue As String 

szCellValue = CStr(Trim(oCell.Value2)) 

' Validate In Dropdown if Length > 0 
If Len(szCellValue) > 0 Then 
    ' See if the oCell value in the oRange loop exists in this szValidationNamedRange dropdown 
    Set oFoundCell = GetRangeFromNamedRange(cValidateCellData.ValidationNamedRange).Find(szCellValue, LookIn:=xlValues, Lookat:=xlWhole) 

    ' If Value Not Found in Dropdown...or if they've typed in an id value (which will be found on odd numbered columns) 
    If oFoundCell Is Nothing Then 
     Call SetError(oCell.Text, cValidateCellData, "Not a Valid Value for drop down " + cValidateCellData.ValidationNamedRange + ".") 
     bError = True 
    End If 

Else 
    If cValidateCellData.Required Then 
     Call SetError(oCell.Text, cValidateCellData, "Please input a value. This is a Required Field.") 
    End If 
End If 
+1

只是一个问题,为什么你的代码验证,如果输入值的范围是因为你已经有一个数据验证列表? –

+1

你可以用'〜'来转义星号。例如:'szCellValue = Replace(szCellValue,“*”,“〜*”)' –

+0

@TimWilliams我认为你应该将它作为答案发布,它正确回答问题并且有用,不是吗? –

回答

1

你可以使用〜来转义星号。

如:

Dim bError As Boolean 

Dim oCell As Range 
Dim oFoundCell As Range 

Dim szCellValue As String 
Dim szLookupValue As String 

szCellValue = CStr(Trim(oCell.Value2)) 

' Validate In Dropdown if Length > 0 
If Len(szCellValue) > 0 Then 
    ' See if the oCell value in the oRange loop exists in this szValidationNamedRange dropdown 
    ' (escape * using ~) 
    Set oFoundCell = GetRangeFromNamedRange(cValidateCellData.ValidationNamedRange) _ 
      .Find(Replace(szCellValue, "*", "~*"), LookIn:=xlValues, Lookat:=xlWhole) 

    ' If Value Not Found in Dropdown...or if they've typed in an id value 
    ' (which will be found on odd numbered columns) 
    If oFoundCell Is Nothing Then 
     Call SetError(oCell.Text, cValidateCellData, _ 
      "Not a Valid Value for drop down " & cValidateCellData.ValidationNamedRange & ".") 
     bError = True 
    End If 

Else 
    If cValidateCellData.Required Then 
     Call SetError(oCell.Text, cValidateCellData, _ 
       "Please input a value. This is a Required Field.") 
    End If 
End If 
+0

我做了这个修复,但它不起作用。 oFoundCell仍然在列表中找到第一个项目 –

+0

查找部分在测试中为我工作,但我无法复制您的整个设置... –

+0

我有一个查找选项卡用于定义范围和用户选项卡,其中用户输入数据。我将列中的每个单元格设置为类型列表的数据验证。 Excel不会阻止用户键入或粘贴到单元格中,因此我试图验证列表中是否存在作为项目的单元格值。不幸的是,如果值是*或〜,oFoundCell指向列表中的第一个条目 –