Search code examples
vbarowcellexcel-2003

Excel 2003 - Macro to delete multiple rows by cell value


Goal: I am looking for a macro that can delete multiple rows based on cell criteria in one column, but I want the macro to ask for a value each time it is run rather than having a set value included in code. Each code that I have found online so far either does not work or is coded for only one value.

I am using excel 2003

Here is the one code that I've found that works for my purpose.. but I would like to edit it somehow so that it prompts the user to input a certain number, rather than use the same number over and over again.

      Sub Delete_Rows()
            Dim rng As Range, cell As Range, del As Range
            Set rng = Intersect(Range("A2:J707"), ActiveSheet.UsedRange)
            For Each cell In rng
            If (cell.Value) = "201" _
            Then
            If del Is Nothing Then
            Set del = cell
            Else: Set del = Union(del, cell)
            End If
            End If
            Next cell
            On Error Resume Next
            del.EntireRow.Delete
        End Sub

Solution

  • You should check the InputBox function

    Basically, it displays a prompt in a dialog box, waits for the user to input text or click a button, and then returns a string containing the contents of the text box.

    So, for your code, it would be like this :

     Sub Delete_Rows()
        Dim selectedValue As Integer
        selectedValue = InputBox ("Please, enter a number", "Input for deleting row", Type:=1)
                                  'Prompt                   'Title                  'Value type (number here)
        Dim rng As Range, cell As Range, del As Range
        Set rng = Intersect(Range("A2:J707"), ActiveSheet.UsedRange)
        For Each cell In rng
        If (cell.Value) = selectedValue _
        Then
        If del Is Nothing Then
        Set del = cell
        Else: Set del = Union(del, cell)
        End If
        End If
        Next cell
        On Error Resume Next
        del.EntireRow.Delete
    End Sub