VBA的Excel数据validation

我正在寻找一些帮助,创build一个工作表“比较”中的C列中的值进行数据validation的基础上C,D,E等列中不同的工作表“映射”中列出的可能值我想有可能的值使用string/模式字符,如#? *使数据validation更灵活。 可能有任何地方从1到5 +以上的不同的可能的价值观,因关键而异。 validation差异将被放入工作表比较的空列D中。

数据示例可能在这里最有帮助。

Static sheet 'mapping' . Key is Column A. Possible values in Columns C onwards ABCDEFG v1 CDID #### ###? 0 c52 FHAID ER# EP# INVA Z* c48 PLID * v24 CUSTID ### ###Q ###P c22 MATID ???# ??# ?# q23 LKKID * Input original sheet 'Compare'. Key is Column B. Column C contains Data to validate ABCD c22 MATID RT3FG v24 CUSTID 456P v1 CDID 5 q23 LKKID PORTA Output sheet 'Compare'. Invalid values noted in Column D. ABCD c22 MATID RT3FG Error: Invalid value v24 CUSTID 456P v1 CDID 5 Error: Invalid Value q23 LKKID PORTA 

任何想法如何使这项工作? 比较工作表将具有所有数据开始在A1没有标题。 映射表将是相当大的100 +行,可能需要一个查找或类似的find正确的行。

假设*是什么#是一个数字和? 是一个字符,我想出了这个

 Sub CompareToMapping() Dim mapSheet As Worksheet: Set mapSheet = Sheets("Mapping") Dim compSheet As Worksheet: Set compSheet = Sheets("Compare") Dim mcell As Range Dim ccell As Range Dim rcell As Range 'Loop throw all the rows in the compare sheet For Each ccell In compSheet.Range("a1", compSheet.Range("a" & compSheet.Rows.Count).End(xlUp)) 'loop through and find a matching row from Mapping sheet For Each mcell In mapSheet.Range("a1", mapSheet.Range("a" & mapSheet.Rows.Count).End(xlUp)) If mcell = ccell And mcell.Offset(0, 1) = ccell.Offset(0, 1) Then 'loop through valid format strings For Each rcell In mapSheet.Range(mcell, mapSheet.Cells(mcell.Row, mapSheet.Columns.Count).End(xlToLeft)) ccell.Offset(0, 3) = "Error: Invalid value" If FormatCorrect(ccell.Offset(0, 2).Text, rcell.Offset(0, 2).Text) Then 'show error in column d ccell.Offset(0, 3) = "" Exit For End If Next rcell Exit For End If Next mcell Next ccell End Sub Function FormatCorrect(inString As String, inFormat As String) As Boolean Dim i As Integer: i = 0 Dim curS, curF As String FormatCorrect = True ' first check for * If inFormat = "*" Then FormatCorrect = True ' next check if strings are the same length ElseIf Len(inString) <> Len(inFormat) Then FormatCorrect = False Else 'compare 1 character at a time For i = 1 To Len(inString) curS = Mid(inString, i, 1) curF = Mid(inFormat, i, 1) If curF = "?" Then ' needs to be a letter If IsNumeric(curS) Then FormatCorrect = False Exit For End If ElseIf curF = "#" Then ' needs to be a number If Not IsNumeric(curS) Then FormatCorrect = False Exit For End If Else ' needs to be an exact match If curF <> curS Then FormatCorrect = False Exit For End If End If Next i End If End Function 

经过testing,为我工作。 祝你好运 :)