简体   繁体   中英

Add multiple rows in Excel starting from same cell value VBA

I have a sheet that has multiple blocks of recurring rows. Something like this:

SALAD
Small
Medium
Large

FRIES
Small
Medium
Large

BURGERS
Small
Medium
Large

How can I add, say, 10 rows in between "Medium" and "Large" in each section?

My sheet has hundreds of these types of sections, so I can't do it manually.

If you want to just add one row, I can use the control + F, search "Large," select all, and add a row. But I'd have to do that each time for each row I want to add, 10 times in total.

Thanks!

You can easily do this with VBA. To get to the VBA editor, press ALT+F11 when in Excel. The create a new module (Insert>Module) and paste the following code:

Sub insertRows()

    Dim vcell As Range
    Dim i As Integer
    Dim j As Integer
    Dim lastRow As Integer

    ' Use WITH for shorthand (everything starting ".")
    ' because all cell references are to current sheet
    With ThisWorkbook.ActiveSheet

        ' Cycle through each cell in the used range of column 1,
        ' start by getting the last row
        lastRow = .UsedRange.Rows.Count

        ' Go bottom to top as inserting new rows pushes everything down
        For i = lastRow To 1 Step -1

            ' Set cell as row i, column 1
            Set vcell = .Cells(i, 1)

            ' If it is a cell with value LARGE then do some action
            If vcell.Value = "Large" Then

                ' loop for desired number of times, e.g. 3
                For j = 1 To 3

                    ' Insert a new row above VCELL
                    vcell.EntireRow.Insert

                Next j

            End If

        Next i

    End With

End Sub

To Run the code press F5 or click the green play button.

I've commented the code (all lines starting with an apostrophe) for explanation. This code cycles up through the column, and when a cell value is "Large", 3 rows are inserted. Of course in your example, change this to 10 and you can later change "Large" to anything you wish.

Below is the result:

之前和之后的专栏

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM