Q:

vba - loop through 3 columns

There are 4 columns on my excel.
For every element in column A, I would like to loop through every element column C. If the element in column C equal to column A, then it return the value of column D in column B.
For example, B4 should return "dog". B5 should return "egg". B6 should return "cat".

I ran my VBA code. All the value in column B returns "egg". Could someone have a look with my below VBA code please?
Sub testing_click()

Dim x As Variant
Dim arr1 As Variant
Dim i , r As Long
arr1 = Worksheets("testing").Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Value

For Each x In arr1
    For r = 1 To 5
    If x = Trim(Worksheets("testing").Cells(r, "c").Value) Then
        For i = 1 To Worksheets("testing").Range("a1048576").End(xlUp).Row
            Worksheets("testing").Cells(i, "b").Value = Worksheets("testing").Cells(r, "d").Value
        Next i
    End If
    Next r
Next x

End Sub

A:

Just had one too many loops in there.  What it was actually doing was finding the first value correctly, and putting it in all 12 rows of column "B".  Then finding the second value, and re-assigning all 12 rows of column "B".  
Get rid of the innermost loop, add counter in it's place with the same name, and you're good to go.  Now, instead of looking through all cells in column "A", it only looks through the populated ones, and will terminate the inner loop as soon as it has a match.
Also corrected a mistake in the declarations.  Dim i, r As Long actually only casts r as long, and i as Variant.  Dim i as Long, r as Long will capture them both as Long types.
Hope it helps!
Sub testing_click()

Dim x As Variant
Dim arr1 As Variant
Dim i as Long, r As Long
arr1 = Worksheets("testing").Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Value

'initialize row counter out here
i = 1
For Each x In arr1
    For r = 1 To 5
        If x = Trim(Worksheets("testing").Cells(r, "c").Value) Then
            Worksheets("testing").Cells(i, "b").Value = Worksheets("testing").Cells(r, "d").Value
            'Increment row counter and exit inner loop
            i = i + 1
            Exit For
        End If
    Next r
Next x

End Sub

