Excel

Delete groups of rows using autofilter with VBA (Delete rows 1-9, 11-19, 21-29 etc)

Ease of Use

Easy

Version tested with

2000, 2003 

Submitted by:

brettdj

Description:

The code will delete groups of rows from row 1 to the last used cell in the selected column. If the user selected to delete every 15 rows in Column B, the code would leave row 16, 32, 48, 64 etc till it reached the last used cell in Column B 

Discussion:

You have a worksheet that needs to keep only the data from every tenth datapoint in Column B Populating a working column with formulas from VBA is an efficient method used in conjunction with autofilter for quickly deleting or keeping certain rows. 

Code:

instructions for use

			

Sub KillRows() Dim Myrange As Range Dim NumKill As Long Dim KillColumn As String Dim ActiveColumn As String Dim AC 'Extract active column as text. Split needs Excel 200 AC = Split(ActiveCell.EntireColumn.Address(, False), ":") ActiveColumn = AC(0) KillColumn = InputBox("Enter Column that will be used to map rows for deletion - press Cancel to exit sub", "Row Delete Code", ActiveColumn) 'test that user has not used column IV If Application.CountA(Range("IV:IV")) > 0 Then MsgBox "There are no spare columns. Macro will exit", vbCritical Exit Sub End If NumKill = InputBox("Input an Integer less than 65536", "How many rows do you want to kill", Default:=15) 'Run from row 1 of the selected column to the last used cell in that column Set Myrange = Range(Cells(1, KillColumn), Cells(65536, KillColumn).End(xlUp)) Application.ScreenUpdating = False If Myrange Is Nothing Then Exit Sub With Myrange.Offset(0, 1) .EntireColumn.Insert .FormulaR1C1 = "=MOD(row(RC[-1])," & NumKill & ")=0" .AutoFilter Field:=1, Criteria1:="FALSE" If .Cells.Count > 0 Then .EntireRow.Delete .EntireColumn.Delete End With Cells(1, KillColumn).Activate Application.ScreenUpdating = True End Sub

How to use:

  1. Open an Excel workbook
  2. Select Tools/Macro/Visual Basic Editor
  3. In the VBE window, select Insert/Module
  4. Copy and paste the code into the Module
  5. Now select File/Close and Return To Microsoft Excel
  6. Save your work
 

Test the code:

  1. Select Tools/Macro/Macros...KillRows
 

Sample File:

KIllRows(KB12).zip 13.78KB 

Approved by mdmackillop


This entry has been viewed 284 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express