I was trying to insert a row just below another row base on some condition. Now this code will loop through many sheets. It work fine for 1 sheet, but when it tries to perform the same function for next sheet, it showing error. Can anybody help me to solve the problem. The code I was using is given below:
Sub test()
Dim a As Worksheet
Dim lngRow As Long
Dim s As String
Dim z As Variant
s = "Sheet1,Sheet2"
z = VBA.Split(s, ",")
For Each i In z
Set a = Sheets(i)
For lngRow = a.UsedRange.Rows.Count To 1 Step -1
If UCase$(a.Cells(lngRow, 2).Value) = "R" Then
a.Range("A" & CStr(lngRow + 1)).Select
Selection.EntireRow.Insert , CopyOrigin:=xlFormatFromLeftOrAbove
End If
Next lngRow
Next i
End Sub
The error is coming in this row:
a.Range("A" & CStr(lngRow + 1)).Select
The reason you get an error is that you can only Select
a range on the Active sheet. To fix your code as is, add a.Activate
before the For
loop.
Better still, don’t Select
at all.
Answer:
your code assumes that Sheets(1) equals sheets(“Sheet1”) which might not be always the case. better use a code like the following:
Sub Test1()
Dim aSht As Variant, SafeShts As String
Dim lngrow As Long
SafeShts = LCase("Sheet3 , Sheet4") 'Write here sheets to be unaffected
For Each aSht In ThisWorkbook.Sheets
If InStr(SafeShts, LCase(aSht.Name)) < 1 Then 'Current sheet not within safe sheets
For lngrow = aSht.UsedRange.Rows.Count To 1 Step -1
If UCase(aSht.Cells(lngrow, 2)) = "R" Then
aSht.Cells(lngrow + 1, 1).EntireRow.Insert xlShiftDown, xlFormatFromLeftOrAbove
End If
Next
End If
Next
End Sub
The code doesn’t select anything before changes, so it is pretty fast to.
Cheers