Hi,
Continuing with my goal to learn VBA and while playing with the following code, I encountered strange behavior of debug statements. In the code below I have put my comments to identify where the "funny behavior" is encountered.
Will appreciate if you can help me understand. I also have a simple request/question at the end of the code below:
Code
Sub Test()
Dim Rng1 As Range
Dim Rng2 As Range
Set Rng1 = Worksheets("Sheet1").Cells(1, 1)
irow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
Set Rng1 = Rng1.Resize(irow - Rng1.Row + 1, 1)
Set Rng2 = Worksheets("Sheet2").Cells(1, 1)
irow = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
Set Rng2 = Rng2.Resize(irow - Rng2.Row + 1, 1)
For Each r1 In Rng1
r1.Interior.ColorIndex = 6
For Each r2 In Rng2
If r2.Value = r1.Value Then
r1.Interior.ColorIndex = xlColorIndexNone
Exit For
End If
Next r2
Next r1
Debug.Print "R1.Value = " & r1.Value
Debug.Print "R1.Address = " & r1.Address
[COLOR="SeaGreen"][B]' Both of the above statements crash the code but the next 2 lines of code do not.
' How come the next 2 lines of code do not crash???[/B][/COLOR]
Debug.Print "R2.Value = " & r2.Value
Debug.Print "R2.Address = " & r2.Address
For Each r2 In Rng2
r2.Interior.ColorIndex = 6
For Each r1 In Rng1
If r2.Value = r1.Value Then
r2.Interior.ColorIndex = xlColorIndexNone
Exit For
End If
Next r1
Next r2
[B][COLOR="seagreen"]' And to make things even more interesting, all of the following 4 lines of code crash???[/COLOR][/B]
Debug.Print "R1.Value = " & r1.Value
Debug.Print "R1.Address = " & r1.Address
Debug.Print "R2.Value = " & r2.Value
Debug.Print "R2.Address = " & r2.Address
End Sub
Display More
Also, what i want to do is that at the end, the very next cell (i.e. 1 row down) of Rng1 and Rng2 should be filled with heavy border and Red fill.
Thanks.