防止重复出现在列中,无论条目大小写如何

问题描述 投票:1回答:4

我在特定单元格中输入三个条目[A2,B2,C2]并运行代码以将此数据带到表中的第一空行。

该代码还根据在单元格B2中输入的值来防止重复。如果它已经存在于(B2:B5000)范围内,则可以防止重复。

问题是它不会忽略这种情况。

例如:输入值“醋酸”一段时间后,我添加“乙酸”或更改任何大写字母。

代码通常在没有阻止的情况下将其添加。

我如何忽略字母大小写?

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
excel vba duplicates case-insensitive
4个回答
1
投票

要在VBA中更改大小写,您需要LCaseUCase,它们分别将所有字符串更改为lower大小写或upper大小写。

这是您的代码,其中有更改,最后使用了无用的(和ressource-greedy)选择:

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

2
投票

感谢您的所有答复,我也将尽力为您提供反馈。

我可以通过在模块顶部添加此行来弄清楚。

Option Compare Text

它解决了我的问题。

谢谢


1
投票

您可以通过将两个值都强制为大写或小写来替换不区分大小写的循环来比较现有值。

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

0
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.