Iron Man
Iron Man

Reputation: 849

Deleting Rows based on column value

I have a code that I have used before in other projects that worked as intended. I am now using this code with a different value. But any row that contains a value other than "WorkGroup Manager" is not getting deleted. I am now working in Excel 2013 (The company just upgraded from 2007). Could this be contributing to the code not working properly? I do not know what the differences would be between Excel 2007 and Excel 2013 as it relates to VBA coding.

Sub Filter_WGM()

    Dim PTASK_Template As Workbook
        Set PTASK_Template = Workbooks("BCRS Unassigned Tasks Template.xlsm")
    Dim WGMd As Worksheet
        Set WGMd = PTASK_Template.Sheets("WGM")

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual


        With WGMd
        Dim LRMf As Long
            For LRMf = Cells(Rows.Count, 3).End(xlUp).Row To 2 Step -1
                If Cells(LRMf, 3).Value <> "WorkGroup Manager" Then
                    Rows(LRMf).Delete
                End If
            Next LRMf
        End With

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

I need to repeat this code with different values to work on two other worksheets after I get it to work for this one.

Upvotes: 2

Views: 45

Answers (1)

Jason Conway
Jason Conway

Reputation: 141

Try this, as suggested I've used the with statement and also re-jigged some of the code to make for easier reading.

Sub Filter_WGM()

Dim PTASK_Template As Workbook
Dim WGMd As Worksheet
Dim LRMf As Long

    Set PTASK_Template = Workbooks("BCRS Unassigned Tasks Template.xlsm") 
    Set WGMd = PTASK_Template.Sheets("WGM")

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    With WGMd
        For LRMf = .Cells(.Rows.Count, 3).End(xlUp).Row To 2 Step -1
            If .Cells(LRMf, 3).Value <> "WorkGroup Manager" Then
                .Rows(LRMf).Delete
            End If
        Next LRMf
    End With

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

Also, if you intend to use this on various sheets and look for various values you could try something along the lines of the following. You can then kick this sub off and pass it the relevant parameters. (Please note this code is untested).

Sub DeleteRowsFromSheet(TargetSheet As Worksheet, ValueColumn As Integer, Value As String)

Dim MyRow As Integer

With TargetSheet
    For MyRow = 2 To .Cells(.Rows.Count,ValueColumn).End(XlUp).Row
        If .Cells(MyRow,ValueColumn).Value <> Value Then   
            .Row(MyRow).EntireRow.Delete
            MyRow = MyRow - 1
        End If
    Next
End With

End Sub

Upvotes: 2

Related Questions