+ Reply to Thread
Results 1 to 5 of 5

Find lastrow and delete rows

Hybrid View

  1. #1
    Registered User
    Join Date
    07-09-2012
    Location
    Minnesota
    MS-Off Ver
    Excel 2007
    Posts
    9

    Find lastrow and delete rows

    Hey everyone!

    These are the steps I am having trouble coding:

    1. Find the last row of a sheet called "Report" based on column A
    2. In column HE, input a formula (=code(RC[-208])) which is supposed to be the code of column B, from HE2 until HE lastrow
    3. Delete entire row if HE=32
    4. Delete entire row if column BO is blank

    I am having the most trouble figuring out what the general syntax for indicating to do something until the last row is. For example, I want to copy a lot of data and past it on a different sheet so how would I say to copy from cell A2:A last row? Or if I wanted to sort from B2:B last row?

    I am very new to VBA so I have been using the macro recorder often which puts all of my code in a difficult to understand format.

    Any help would be appreciated!

    Thanks so much!

  2. #2
    Forum Expert tigeravatar's Avatar
    Join Date
    03-25-2011
    Location
    Colorado, USA
    MS-Off Ver
    Excel 2003 - 2013
    Posts
    5,361

    Re: Find lastrow and delete rows

    tableq,

    This macro accomplishes what you described. It uses a loop (which I don't really recommend, but its much easier to follow for beginners than autofilter code) and can easily be adapted to fit your requirements. I commented the code as much as possible in order to explain what was going on.
    Sub tgr()
        
        'Declare variables
        Dim lLastRow As Long        'Will be used to store the row number of the last row
        Dim rIndex As Long          'Will be used to loop backwards from the last row to row 2
        Dim lCalc As XlCalculation  'Will be used to store the workbook's calculation state
        
        'Disable items to allow macro to run faster
        With Application
            lCalc = .Calculation                'Store workbook's calculation state
            .Calculation = xlCalculationManual  'Set workbook calculation to manual
            .EnableEvents = False               'Turn off events (prevents event triggered code from running)
            .ScreenUpdating = False             'Turn off screen updates (prevents screen flickering while macro runs)
        End With
        
        'Assume code will fail and put in an error handler
        On Error GoTo CleanExit
        
        'This section is the workhorse of the code
        With ActiveWorkbook.Sheets("Report")    'Make sure the code runs on the correct sheet
            lLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row   'Get the last used row in column A
            For rIndex = lLastRow To 2 Step -1                  'Loop through the rows starting at the last row and going backwards to row 2
                If Len(Trim(.Cells(rIndex, "BO").Value)) = 0 Then   'Check if cell BO in the current row is empty
                    .Rows(rIndex).Delete xlShiftUp  'Found it is empty, delete the row
                Else
                    .Cells(rIndex, "HE").FormulaR1C1 = "=CODE(RC[-211])"                   'Found it is not empty, enter the formula in cell HE of the current row
                    If .Cells(rIndex, "HE").Value = 32 Then .Rows(rIndex).Delete xlShiftUp  'If the formula results in 32, delete the row
                End If
            Next rIndex 'Advance the loop
        End With    'Done working with the sheet
        
    'If there was an error at any point, the code will automatically go straight to this section, skipping the rest
    'If there was no error, the code goes to this section anyway
    'This section is designed to allow the macro to cleanly exit
    CleanExit:
    
        'Re-enable the items we turned off earlier
        With Application
            .Calculation = lCalc    'Set the workbook calculation back to its original state
            .EnableEvents = True    'Turn events back on
            .ScreenUpdating = True  'Turn screen updates back on
        End With
        
        'If there was an error, display the error message and clear the error
        If Err > 0 Then
            MsgBox Err.Description, , "Error: " & Err.Number
            Err.Clear
        End If
        
    End Sub


    EDIT: Good catch on those, WasWodge, code has been updated with the corrections.
    Last edited by tigeravatar; 07-24-2012 at 10:39 AM. Reason: Updated code to reflect corrections noted by WasWodge
    Hope that helps,
    ~tigeravatar

    Forum Rules: How to use code tags, mark a thread solved, and keep yourself out of trouble

  3. #3
    Valued Forum Contributor WasWodge's Avatar
    Join Date
    08-02-2010
    Location
    Hampshire,England
    MS-Off Ver
    Office 365 and Office 2010
    Posts
    882

    Re: Find lastrow and delete rows

    (=code(RC[-208])) which is supposed to be the code of column B
    I think the offset needs to be -211 and not -208 to get column B from Column HE

    I think there also needs to be 1 less bracket in tigeravatar's code i.e.

    .Cells(rIndex, "HE").FormulaR1C1 = "=code(RC[-211]))"
    to
    .Cells(rIndex, "HE").FormulaR1C1 = "=code(RC[-211])"
    Last edited by WasWodge; 07-23-2012 at 07:42 PM.
    If my solution worked (or not) please let me know. If your question is answered then please remember to mark it solved

    Computers are like air conditioners. They work fine until you start opening windows. ~Author Unknown

  4. #4
    Registered User
    Join Date
    07-09-2012
    Location
    Minnesota
    MS-Off Ver
    Excel 2007
    Posts
    9

    Re: Find lastrow and delete rows

    Thank you both so much! That worked really well!

    If i wanted to copy data from the report sheet to a sheet called NORMDataSheet, and I wanted it to capture all the data from row 2 until the last row, could I use the syntax:

    Sheets("Report").Select
        Cells(rIndex,"A").Select
        Selection.Copy
        Sheets("NORMDataSheet").Select
        Range("B2").Select
        ActiveSheet.Paste
    Right now I have all my code in the format

    Range("B2:B100")
    simply due to the fact that I was unsure of how to make everything go through the last row. So if i change all of it to:

    Cells(rIndex,"B")
    for example, will this work throughout my code?
    Last edited by Cutter; 07-24-2012 at 06:54 PM. Reason: Added code tags

  5. #5
    Valued Forum Contributor WasWodge's Avatar
    Join Date
    08-02-2010
    Location
    Hampshire,England
    MS-Off Ver
    Office 365 and Office 2010
    Posts
    882

    Re: Find lastrow and delete rows

    If I was doing it then I would probably use something like the code below and then just use MYRNG throughout the code.

    Sub GetCells()
        Dim MYRNG As Range
        Dim LastCol As Long
        LastCol = Sheets("Report").Cells.Find(what:="*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        Set MYRNG = Sheets("Report").Range([a2], Cells(Rows.Count, LastCol).End(xlUp))
    
        MYRNG.Copy
        Sheets("NORMDataSheet").Range("B2").PasteSpecial
        
        Application.CutCopyMode = False
    End Sub

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1