VBA to delete all rows NOT equal to value in inputbox

Dustinkli

Board Regular
Joined
Mar 26, 2019
Messages
62
Office Version
  1. 365
  2. 2011
Platform
  1. Windows
Hello,


I would like to be able to delete all rows in a spreadsheet based on a specified value in a selected column. I currently have a macro to delete a row based on specified cells but I'm not sure how to make it delete all rows with cells in a column EXCEPT a specified cell based on an input box. The one I have is based on .autofilter but I don't know if it has the capability to do what I need.

Basically I'd like to put the cell to preserve and it deletes all rows where that cell isn't in that column.

Can anyone point me in the right direction?
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
What about you post the code you have and it would probably just require a slight modification to do the new job.

About how many rows of data altogether are you likely yo have in your sheet?
 
Upvote 0
I think I found a solution:

Code:
Sub DeleteRows()
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
xTitleId = "DeleteRows"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Select Column Range :", xTitleId, InputRng.Address, Type:=8)
DeleteStr = Application.InputBox("Text to Preserve", xTitleId, Type:=2)
For Each rng In InputRng
    If rng.Value <> DeleteStr Then
        If DeleteRng Is Nothing Then
            Set DeleteRng = rng
        Else
            Set DeleteRng = Application.Union(DeleteRng, rng)
        End If
    End If
Next
DeleteRng.EntireRow.Delete
 End Sub
 
Upvote 0

Forum statistics

Threads
1,223,886
Messages
6,175,190
Members
452,616
Latest member
intern444

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