PDA

View Full Version : Removing Rows Based On One or More Cell Values



Baiano42
08-02-2019, 04:42 AM
Good morning,

I am trying to generate a macro that would auto set the range I use ("$A$1:$O$1000"), and give the user the option to input one or more criteria to search and delete rows for.
I found this code at https://www.extendoffice.com/documents/excel/1747-excel-delete-row-if-zero.html:


Sub DeleteRows()'Updateby20140314
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
xTitleId = "KutoolsforExcel"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
DeleteStr = Application.InputBox("Delete Text", 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

The difference I need from it is to preset the specified range and loop through the "Delete Text" part until the user is satisfied and presses "Cancel".)

I also found a similar macro (Delete_Rows_User_Input) here: https://www.excelcampus.com/vba/delete-rows-cell-values/, but it would give an error when trying to run it pointing to the

Set lo = Sheet1.ListObjects(1) part of the code.

My end goal would be to click the macro and have it run an Import .txt file->loop Delete Rows Based on Cell Values->Save as .txt
I already have the Import .txt and save as .txt portions of the macro, I just need the last part. Thanks!

Baiano42
08-02-2019, 09:28 AM
So poking with the code, I replaced this portion of code:

Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
with:

Set InputRng = Range("$A$1:$O$1000").SelectIt selects the desired cell range when I run it. However, it gives me the error:
Run-Time Error '424':
Object Required
How can I use this range selection, and take out the need for that InputBox?

Update:
I used the following and now the macro uses the desired range:

Set InputRng = Application.Intersect(Range("$A$1:$O$1000"), Range("$A$1:$O$1000"))

Now:
1. How can I adjust the code to repeat (or have two inputs for the delete portion of the code) until it is canceled?
2. How do I prevent the: "Run-time error '91': Object variable not set"?

The Code at present:

Sub Delete_Rows_User_Input()'Updateby20140314
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
xTitleId = "Delete Rows"
Set InputRng = Application.Selection
Set InputRng = Application.Intersect(Range("$A$1:$O$1000"), Range("$A$1:$O$1000"))
DeleteStr = Application.InputBox("Select Valuse to Delete", 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