当A列中的值为1

时间:2017-11-15 22:54:46

标签: excel vba excel-vba

我想在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

2 个答案:

答案 0 :(得分:1)

以下代码已经过测试和运作。

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

答案 1 :(得分:0)

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行,所以我们也增加了LastRow变量。我们不能在VBA中的for循环中执行此操作,for循环将在20处终止,因此我已更改为while循环

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