Excel VBA代码:防止列中出现重复,而不考虑条目的敏感情况

我正在使用vba代码将数据input到表中,我在特定单元格[A2,B2,C2]中键入3个条目,并运行代码将此数据提取到表中的第一个空行。

如果代码已经存在于范围(B2:B5000)中,则代码还可以防止基于单元格B2中input值的数据重复,从而防止重复。 但问题是它不忽略敏感的情况,例如:我input值“乙酸”一段时间后,我想添加另一个项目,这样键入它(乙酸)或改变任何字母的情况下,代码添加通常没有阻止。 所以有什么build议请忽略字母大小写? 使用的代码是:

Sub tarheel() LastRow = Range("A10000").End(xlUp).Row + 1 LR = Range("b10000").End(xlUp).Row + 1 For r = 5 To LR If Cells(r, 2) = Range("b2") Then MsgBox "This Item Name already exist, No shift will done": Exit Sub Next Cells(LastRow, 1).Value = Range("A2").Value Cells(LastRow, 2).Value = Range("B2").Value Cells(LastRow, 3).Value = Range("C2").Value Range("A2:C2").Select Selection.ClearContents Range("A2").Select End Sub 

要改变VBA的情况,你有LCaseUCase ,它们将分别把你所有的string变成小写大写

这里是你的代码随着变化,并得到无用的(和资源 – 贪婪)select在最后:

 Sub tarheel() LastRow = Range("A10000").End(xlUp).Row + 1 LR = Range("b10000").End(xlUp).Row + 1 IsIn = False For r = 5 To LR If LCase(Cells(r, 2)) = LCase(Range("b2")) Then _ MsgBox "This Item Name already exist, No shift will done": Exit Sub Next Cells(LastRow, 1).Value = Range("A2").Value Cells(LastRow, 2).Value = Range("B2").Value Cells(LastRow, 3).Value = Range("C2").Value Range("A2:C2").ClearContents 'Range("A2").Select End Sub 

感谢所有的答复,我也会尝试,并给你反馈。

我可以通过在我的模块的顶部添加此行来解决这个问题。

 Option Compare Text 

它解决了我的问题。

谢谢

您可以将您现有的值与不区分大小写的值进行比较,将这两个值强制为大写或小写。

 For r = 5 To LR If lcase(Cells(r, 2)) = lcase(Range("b2")) Then MsgBox "This Item Name already exist, No shift will done" Exit Sub end if Next 

使用不区分大小写的工作表函数一次检查整个范围可能更有效。

 If cbool(application.countif(Range("B5:B" & LR), Cells(r, 2))) Then MsgBox "This Item Name already exist, No shift will done" Exit Sub end if 

另一个可能:

 If not iserror(application.match(Cells(r, 2), Range("B5:B" & LR), 0)) Then MsgBox "This Item Name already exist, No shift will done" Exit Sub end if