From my tests, it appears that a reference to the range C2: C18 (in the test - the variable Rng) behaves differently. When the first or last cell of a range is deleted, this reference changes its address. However, if cells from the second to the penultimate one are deleted - the reference remains unchanged. I cannot explain why removing cells at the borders changes the address, and removing cells inside does not.
Macro for testing only:
Sub CleanUp_Test_Art()
Dim lastrow As Long
Dim cel As Range
Dim Rng As Range
'this will move region to column b and leave a 2nd location if there is one in column a
lastrow = Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Range("A2:A" & lastrow)
Debug.Print "Rng.Address: " & Rng.Address
For Each cel In Rng
Debug.Print cel.Address(0, 0) & " | " & IIf(InStr(cel.Value, ":") > 0, "To insert", "It remains")
If InStr(cel.Value, ":") > 0 Then
cel.Insert Shift:=xlToRight
End If
Debug.Print IIf(InStr(cel.Value, ":") > 0, "After insert: ", "After: ") & cel.Address(0, 0)
Debug.Print "Rng.Address: " & Rng.Address(0, 0)
Next cel
Debug.Print String(10, "- ")
'remove photo lines out of Column C
Set Rng = Range("C2:C" & lastrow)
Debug.Print "Rng.Address: " & Rng.Address
On Error Resume Next
For Each cel In Rng
Err.Clear
Debug.Print cel.Address(0, 0) & " | " & IIf(InStr(cel.Value, ":") > 0, "To delete", "It remains")
If InStr(cel.Value, "photo") > 0 Then
cel.Delete Shift:=xlToLeft
End If
Debug.Print "After: " & cel.Address(0, 0)
If Err.Number <> 0 Then
Debug.Print Err.Description
End If
Debug.Print "Rng.Address: " & Rng.Address(0, 0)
Next cel
End Sub
Another solution to the problem is to use a descending loop:
Sub CleanUp_Art2()
Dim lastrow As Long
Dim cel As Range
Dim Rng As Range
Dim i As Long
'this will move region to column b and leave a 2nd location if there is one in column a
lastrow = Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Range("A2:A" & lastrow)
For Each cel In Rng
If InStr(cel.Value, ":") > 0 Then
cel.Insert Shift:=xlToRight
End If
Next cel
'remove photo lines out of Column C
For i = lastrow To 2 Step -1
If InStr(Cells(i, "C").Value, "photo") > 0 Then
Cells(i, "C").Delete Shift:=xlToLeft
End If
Next i
End Sub
Artik
Bookmarks