Excel VBAmacros在列A中的值为1时添加一个空行

我想在excel vba中添加一行,当列A中的值为1时,这里是我写的代码,但是这会返回一个“下标超出范围错误”。 我究竟做错了什么?

Sub InsertRow() Dim Col As Variant Dim BlankRows As Long Dim LastRow As Long Dim R As Long Dim StartRow As Long Application.ScreenUpdating = False Col = "A" StartRow = 1 LastRow = 20 Worksheets("Sheet1").Activate For R = StartRow To LastRow If Cells(R, Col) = 1 Then Cells(R, Col).EntireRow.Insert Shift:=xlDown End If Next R Application.ScreenUpdating = True End Sub 

以下代码经过testing和工作。

 With Worksheets("Sheet1") Dim cntr as Long For cntr = 20 to 5 Step - 1 If .Cells(cntr, 1) = 1 Then .cells(cntr,1).EntireRow.Insert Shift:=xlDown Next End With 
 Sub InsertRow() Dim Col As Variant Dim BlankRows As Long Dim LastRow As Long Dim R As Long Dim StartRow As Long Application.ScreenUpdating = False Col = "A" StartRow = 1 LastRow = 20 Worksheets("Sheet1").Activate R = StartRow Do While R <= LastRow If Cells(R, Col) = 1 Then Cells(R, Col).EntireRow.Insert Shift:=xlDown R = R + 1 LastRow = LastRow + 1 End If R = R + 1 Loop Application.ScreenUpdating = True End Sub 

注意循环中R值的设置,当你向下移动行时,你不断地检查相同的值,因此每次增加一行,所以我们需要将R增加1来跳过刚刚检查过的1 。

我们还需要改变端点,因为我们通过插入来推动第20行的值,所以我们也增加了LastRowvariables。 我们不能在VBA中的for循环中执行此操作,for循环将在20结束,因此我已经更改为while循环

根据下面的评论,从20开始反向工作要多得多,但是因为我没有想到我没有把它放在这里:)