簡體   English   中英

Excel VBA宏以在A列的值為1時添加空白行

[英]Excel VBA Macro to add a blank row when the value in column A is 1

我想在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"
        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
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開始倒退工作要困難得多,但是由於我沒有想到這一點,所以我沒有將它放在這里:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM