Why can't this VBA Excel code read duplicates?

送分小仙女□ 提交于 2019-12-13 11:14:57

问题


    r = 11

Do While Not tgtWSheet.Cells(r, 2) = "0"

    If tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 1, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 2, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 3, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 4, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 5, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 6, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 7, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 8, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 9, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 10, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 11, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 12, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 13, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 14, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 15, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 16, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 17, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 18, 2) Then

        MsgBox "Duplicate Record Found!"
        Exit Sub

    Else

        r = r + 1

    End If

Loop

回答1:


I think you should try "And" instead of "Or". The reason is because of a logic issue. I think someone has asked this question before. You can refer to the following post for some help.

check a record for Duplicates Records, Before Creating New Records

Anyway, his chain of thought is to give a name to the column and check if there is any duplicate in the row using the following formula.

rst.FindFirst "[ID] <> " & Me.ID & _
 " AND [TitleText] = '" & Me.TitleText & _
 "' AND [UnitCode] = " & Me.UnitCode & _
 " AND [AcademicYear] = " & Me.AcademicYear & _
 " AND [Titleofchapterjournalarticle] = '" & Me.Titleofchapterjournalarticle & "'"

Hope it helps.



来源:https://stackoverflow.com/questions/35592902/why-cant-this-vba-excel-code-read-duplicates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!