Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Loop automatically kicks out if If statement is true VBA?

I am working on an Excel macro that should find any cells with duplicate IDs and highlight them in red. For some reason, when it finds a duplicate it will exit out of the loop. It cycles through fine if there are not any duplicates. My code is below.

Sub FindNew()

'

' FindNew Macro

'

Dim numRowsThis As Integer

Dim numRowsData As Integer

Dim dataCell As String

Dim thisCell As String

numRowsThis = Sheet5.Cells(2, 2).Value

numRowsData = Sheet5.Cells(1, 2).Value

Dim i As Integer

Dim j As Integer

For i = 1 To numRowsData

dataCell = "A" & LTrim(Str(i))

For j = 4 To numRowsThis

thisCell = "B" & LTrim(Str(j))

If Sheet3.Range(dataCell).Value = Sheet5.Range(thisCell).Value Then

Range(dataCell).Select

With Selection.Interior

.Pattern = xlSolid

.PatternColorIndex = xlAutomatic

.Color = 255

.TintAndShade = 0

.PatternTintAndShade = 0

End With

Range(thisCell).Select

With Selection.Interior

.Pattern = xlSolid

.PatternColorIndex = xlAutomatic

.Color = 255

.TintAndShade = 0

.PatternTintAndShade = 0

End With

End If

Next

Next

'

End Sub

Update:

I'm sorry. There was poor trouble shooting on my part. It does not break out of the loop. For some reason, the statement is never again evaluated as true. I have tried removing all of the code inside the If statement and adding just a msgbox that displays the cell locations of the duplicates. It still does not account for multiple duplicates.

1 Answer

Relevance
  • puaka
    Lv 5
    10 years ago
    Favorite Answer

    Glad you are experimenting with your macros. Some tips

    Range(dataCell).Select could mess up your macro as it makes it the new activecell.

    Create 2 named ranges by using Set keyword

    dim rangeA as range

    set rangeA = sheet1.range("a1:a20")

    or set rangeA = sheet1.range("a1").resize(20,1)

    ' I prefer these to cells(n,n) convention which is hard to read

    Next run a loop within a loop.

    dim cella, cellb as range

    For each cella in rangeA

    For each cellb in rangeB

    if cella = cellb then

    with cella 'there is no need to select the cell to do any changes

    .color = vbred

    end with

    Next

    Next

Still have questions? Get your answers by asking now.