我试图在某些条件下在另一行下方插入一行。现在这段代码将遍历许多工作表。它适用于1张,但是当它尝试为下一张纸执行相同的功能时,它显示错误。任何人都可以帮我解决问题。我使用的代码如下:
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
错误出现在这一行:
a.Range("A" & CStr(lngRow + 1)).Select
答案 0 :(得分:2)
您收到错误的原因是您只能在活动工作表上Select
范围。要按原样修复代码,请在a.Activate
循环之前添加For
。
更好的是,根本不要Select
。
答案 1 :(得分:1)
您的代码假定Sheets(1)等于sheet(“Sheet1”),这可能并非总是如此。更好地使用如下代码:
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
代码在更改之前没有选择任何内容,所以它非常快。
干杯