Excel VBA宏,用于在列a中的值为1时添加空行
当列a中的值为1时,我想在excel vba中添加一行,下面是我编写的代码,但这会返回一个下标超出范围的错误。我做错了什么Excel VBA宏,用于在列a中的值为1时添加空行,vba,excel,Vba,Excel,当列a中的值为1时,我想在excel vba中添加一行,下面是我编写的代码,但这会返回一个下标超出范围的错误。我做错了什么 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
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
下面的代码经过测试,可以正常工作
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
请注意循环中R值的设置,当您向下移动行时,您会不断检查相同的值,因此每次都会添加一行,因此我们需要将R增加1以跳过刚才检查的1
我们还需要更改端点,因为我们正在通过插入将值推过第20行,所以我们还需要增加LastRow变量。我们无法在VBA中的for循环中执行此操作,for循环将在20处终止,因此我已更改为while循环
根据下面的注释,从20开始向后工作要更为明显,但是因为我没有想到我还没有把它放在这里:
你会在包含1的那个行之后添加空白行吗?它不应该给出一个下标的范围错误,但是它也不会做你想做的。您可能希望R=LastRow开始执行步骤-1,也可能希望CellsR+1,Col.EntireRow.Insert Shift:=xldown哪行给出了下标超出范围的错误?我假设这与循环有关,但它实际上是在工作表Sheets1.Activate语句中吗?这意味着您没有一张名为Sheet1的工作表。@SEarle1986:我有一张a列中有数字的工作表,其余列中有一些其他值,如果a列中的数字是1,那么我必须在上面插入一行that@YowE3K当前位置我的错,你是对的。我以为所有的床单在内部都会被命名为Sheet1 et。不管怎样,都要感谢bunchWhich line@goog?。你们有叫Sheet1的工作表吗?如果没有,请修改该名称以适应Excel中的实际选项卡。您还需要将循环再扩展几次。例如,如果每第二行有1行,则只需插入5行新行。注意:仅使用R=LastRow来启动步骤-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
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