vba to insert row based on criteria

drewbny

Board Regular
Joined
Jan 16, 2011
Messages
98
Hi, how can i create a macro to insert rows based on a name of a cell in a column meeting some criteria?

for example, i have a sheet where i want to insert a row above any row where the cell in column C = North Florida.

also could i create a macro where i insert a row above the row in column c = North Florida and copies the formula from the row below it?
 

Excel Facts

Excel motto
Not everything I do at work revolves around Excel. Only the fun parts.
Try this:
VBA Code:
Sub InsertAbove()
'https://www.mrexcel.com/board/threads/vba-to-insert-row-based-on-criteria.1213482/
'inserts row above text you input for found in the C column.
Dim LastRow As Long
Dim SearchFor As String

'find the last row
LastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row

'pop an input box to search for a specific string (North Florida)
SearchFor = InputBox("Input text to insert row above", "Insert Above")

'If SearchFor is empty, you hit Cancel
If SearchFor = "" Then End

'loop through all the rows starting at the bottom
For i = LastRow To 1 Step -1
    'if the string you're looking for is in column C
    If Cells(i, 3).Text = SearchFor Then
        
        'copy the whole row (rem out if you don't want to copy the whole row.
        Rows(i).Copy
        'paste it.  It will carry all info, including formulas from the following row.
        Rows(i).Insert
        
        'if you only want to copy the C column formula from the line below, rem out "Rows(i).Copy" and unrem this next line
        'Cells(i, 3) = Cells(i + 1, 3).Formula
        
    End If
Next
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,220
Messages
6,123,695
Members
449,117
Latest member
Aaagu

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top