VBA loop to insert row based on numeric range

alec_DLW

New Member
Joined
May 4, 2014
Messages
2
Hi,

I am new to this forum and need some help to insert rows based on criteria in a spreadsheet (csv) with 40 columns and <100,000 rows.

I need to insert a row based on a range of +- 600 such that if B2 is within +- 600 of B1 DO NOT insert row. If B2 > B1 by >600 THEN insert row and mark row with increasing numbers 1,2,3,4.... to count inserted rows. This needs to done throughout entire spreadsheet.

An example is below
1250
2400
3450
4600
51500
61700
74000

<tbody>
</tbody>

VBA to sort spreadsheet to:
1250
2400
3450
4600
#1
51500
61700
#2
74000

<tbody>
</tbody>

Thanks
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
This code inserts the rows without the numbering, do the numberings need to have the # symbols?

Code:
Sub InsertRows()
    For I = Range("A" & Rows.Count).End(xlUp).Row To 2 Step -1
        If Abs(Range("B" & I) - Range("B" & I - 1)) >= 600 Then
            Rows(I).Resize(1).Insert
        End If
    Next I
End Sub

Run on sample data
 
Upvote 0
Thanks Momentman.

No the the numberings do not need to the # symbol. I am new to VBA and am not sure if I can run the code you have posted as is? I seem to get an error for the line "If Abs(Range.....)"

Thanks again
 
Upvote 0
A few things, confirm your data as posted in columns A and B 'cos i ran the code and it works fine

Do your columns have headers? If they do, change the "2" un the For I =.... to "3"

Code:
For I = Range("A" & Rows.Count).End(xlUp).Row To 3 Step -1
 
Upvote 0

Forum statistics

Threads
1,216,116
Messages
6,128,930
Members
449,479
Latest member
nana abanyin

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