VBA Macro to Delete Rows Based on Cell Values

Поделиться
HTML-код
  • Опубликовано: 22 июл 2024
  • Sign up for our Excel webinar, times added weekly: www.excelcampus.com/blueprint...
    In this video I explain how to use VBA to delete rows based on cell values or conditions. Download the Excel file that contains the sample code: www.excelcampus.com/vba/delet...
    This is a simple two step process to apply a filter to a range or Table, then delete the visible rows. In the video I explain the VBA code to automate the process with a macro.
    I also share more a few advanced macros that:
    1. Display a message box with the number of rows to be deleted.
    2. Apply filters to multiple columns to delete cells based on multiple conditions or criteria.
    To filter the range or Table we use the AutoFilter method in VBA.
    We then use the SpecialCells method to select the visible cells and delete the entire rows from the range.
    ***Free webinar on Macros & VBA***
    If you're new to macros and/or want to learn more, join me for a free upcoming webinar on "The 7 Steps to Getting Started with VBA".
    You will learn how to write your first macro and go beyond the limitations of the macro recorder.
    👉Click here to register: www.excelcampus.com/macros-we...
    ****************************************************************
    Here are some links and resources:
    Articles on the AutoFilter method in VBA: www.excelcampus.com/vba/macro...
    Video on how to copy & paste visible cells only: • Copy & Paste Visible C...
    Delete entire blank rows: • How to Delete Blank Ro...
    Copy and paste to another workbook with VBA: • VBA Macro to Copy Data...
    Add a Yes/No message box before a macro runs: • How to Add a Yes No Po...
    00:00 Introduction
    00:10 VBA Macro to Delete Rows Based on Cell Values
    01:01 The Process Explained
    05:43 The VBA Macro Code

Комментарии • 81

  • @ExceliAdam
    @ExceliAdam 5 лет назад +1

    Thanks for describing the possibility of deleting rows with VBA so precisely

  • @9019828585
    @9019828585 2 года назад +1

    Great video ! Working absolutely fine , thanks a ton !

  • @tannertucker22
    @tannertucker22 5 лет назад +2

    Another awesome, well-explained video. Thank you Jon.

    • @ExcelCampus
      @ExcelCampus  5 лет назад

      Thanks so much Tanner! :-)

    • @tannertucker22
      @tannertucker22 5 лет назад

      @@ExcelCampus Well-deserved. Have you thought about adding how to preserve the deleted rows by pasting them to a new worksheet?

  • @angon25
    @angon25 4 года назад +1

    New favorite channel!!!

  • @guideglobal2140
    @guideglobal2140 2 года назад +1

    Thank you. Very helpful. If you can provide versions of this for different scenarios (eg, already active sheets as well as new sheets), this would be helpful. Great video.

  • @stephaniealdana8624
    @stephaniealdana8624 4 года назад +1

    This was a life safer! Thank you!!

  • @shawdowsanddust5301
    @shawdowsanddust5301 3 года назад +1

    Outstanding code. Thank you sir.

  • @anthonylobello5365
    @anthonylobello5365 4 года назад +1

    This is excellent Jon. Thank you. Do you how I can use vba (without the autofilter) to delete rows that have a cell in column A with a blank OR a date (any date in it)? Thank you.

  • @qianpiscessay4728
    @qianpiscessay4728 4 года назад +1

    Thanks for such good video.

  • @ca.lakshminarayanreddyjamb9087
    @ca.lakshminarayanreddyjamb9087 5 лет назад

    Awesome Jon.

  • @michaelmurphy5999
    @michaelmurphy5999 4 года назад +1

    Thank you, this is so much easier than trying to write a loop. How about a scenario where a column contains rows with either text or numbers and delete only those where the cell contains text only?

  • @adriansolvi7096
    @adriansolvi7096 5 лет назад

    Great video!!!

  • @sonyarodriguez9572
    @sonyarodriguez9572 5 лет назад

    Hi Jon, I would like the field to apply to multiple columns, do I simple add Field:4,5,6 for example?

  • @Trupticool
    @Trupticool 3 года назад +1

    Thank you very much, very useful video

  • @Dina_Darling
    @Dina_Darling 5 лет назад +2

    Awesome. Thanks!

  • @rajeshmajumdar4999
    @rajeshmajumdar4999 5 лет назад +1

    Thank you👍

  • @tannertucker22
    @tannertucker22 Год назад

    Your lessons are fantastic. Do you know how to edit the code to delete the entire row if the row contains a cell in column B with a strike through please?

  • @srinivasannarayanaswami5378
    @srinivasannarayanaswami5378 2 года назад +1

    Simply Superb. Very useful for me. Appreciate it :-)

  • @empty_mirror
    @empty_mirror 4 года назад +1

    Thank you! :)

  • @scottgaines2677
    @scottgaines2677 3 года назад +1

    Another great video Jon! Thanks so much for the help! Keep the lessons coming please!! :). I'm curious- why you didn't use Current Region rather than cell values when defining the range. Thanks!

    • @scottgaines2677
      @scottgaines2677 3 года назад

      I answered my own question. when using current region, and running the filter, my header row was deleted along with my filtered data. Looking at Jon's example, I see he moved down 1 row when running the delete versus setting the filter. Can't do that with current region. :) Thanks again for another great video Jon!

  • @giuliagrigoli5886
    @giuliagrigoli5886 5 лет назад

    Great video! thanks a lot or that!

  • @Msantora908
    @Msantora908 4 года назад

    Question - Say I want to run a “does not begin with” filter and then delete all those rows. How do you go about doing that? Thanks!

  • @creatorshappylife1256
    @creatorshappylife1256 2 года назад +1

    Thank you so much

  • @redfeather22sa
    @redfeather22sa 4 года назад +1

    Your Very Good !! :) Thank You from SO !! :)

  • @vijaysahal4556
    @vijaysahal4556 4 года назад +1

    very useful sir 👍👍👍👍👍👍

  • @md.saifulislamtuku9303
    @md.saifulislamtuku9303 5 лет назад +1

    Thanks

  • @MohAboAbdo
    @MohAboAbdo 5 лет назад +1

    Thanks ... Thanks

  • @canefan17
    @canefan17 4 года назад +1

    Can it delete rows that meet IF logic? E.g if column C date is less than column G date, then delete.

  • @HowtoHacks
    @HowtoHacks 3 года назад

    Is there a way to prevent the macro from going into debug mode when no target values are present? Say I am targeting blanks and there isn't any blanks. If the button is hit it goes into debug mode.

  • @yisrael1663
    @yisrael1663 4 года назад

    How do I apply AutoFilter for all rows with dates prior to today's date in VBA, then delete the rows?

  • @areliarana1351
    @areliarana1351 9 месяцев назад +1

    🎉 Genius

  • @lenorawillis-photonobics4182
    @lenorawillis-photonobics4182 4 года назад +1

    Hi Jon, great video. I have a question. I have a spreadsheet with about 9,000 people on it that consist of male, females and their addresses. I need to delete only the males from this spreadsheet. How do I create a formula for that.

  • @Sarfoo93
    @Sarfoo93 4 года назад

    What if No Data "Product 2" in the selected range to delete! will macro stop? Or it will proceed with next step. How to record macro for this check?

  • @carlosgaspar4207
    @carlosgaspar4207 3 года назад

    Taking advantage of the availability of help, I am having difficulties in this topic:
    Any delete in "PPP" product, on main data in table(sheet1), the same must be happen in the sheet table of the product "PPP" on sheet2. The ID of the rows are different in each tables. How to to do that?
    Have you any video to solution that?
    Thank you Mr jon

  • @Monnet6777
    @Monnet6777 Год назад

    First of, great video Jon, you show many scenarios to apply vba and delete data. I 've a question. My table has data like CodeSaler,Name, Start Date (yymmdd hhmmss), Final Date (yymmdd hhmmss), Total time duration. How can I delete all repeat name according the conditions ie: the date (take in main that the column date are aplied for a month), and considert the total duration time, but only if the total duration row has the mayor time betwwen all repeats name that is necesary apply the VBA?

  • @tamilsnowgreen
    @tamilsnowgreen 3 года назад

    sir can you tell us if the criteria is not met what should do? for eg. i want this filter for all months but if there is no blanks in some scenarios?

  • @alexandresirois8338
    @alexandresirois8338 4 года назад

    Works great, but my excel keeps crashing at the end of the code before clearing the filter. Any idea why that might happen?

  • @mjchrist828
    @mjchrist828 5 лет назад +1

    I'm doing this, but I'm getting a "runtime error '9', subscript out of range" in reference to the ws = ThisWorkbook.Worksheets("Regular Range"). Any idea what the issue could be? Could it be linked to the fact that the worksheet I'm trying to use this for has more than the usual A-Z columns, and goes into AB,AC,AD, etc?

    • @forexbeat
      @forexbeat 5 лет назад

      Please enter the correct sheet name. Regular range is the sheet name of this youtuber might not be yours

  • @Railien24
    @Railien24 4 года назад

    If i wanted to use two cells side by side as a simple calculator I.e put the number 3 in the left cell and it gets added to the right cell while also removing the 3 so the cell can be used again, how would one do that?

  • @sekarr261
    @sekarr261 4 года назад

    Hi., i have multiple rows with values and empty values after the = (equal sign). row values similar to _inst__rotz_units = , _inst__rotz_label = RotZ, _inst__y_access = etc., How to delete the rows, which has empty value after equal sign,

  • @stevesandike252
    @stevesandike252 4 года назад +3

    subscript out of range before it starts, on the set ws line

    • @nitebone
      @nitebone 3 года назад

      I change the "text" to the sheet number and it worked for me.

  • @monicathatcher1917
    @monicathatcher1917 4 года назад

    what if you want to find duplicate names and delete the duplicate row for a specific name, then move to the next set of duplicate names.

  • @nitebone
    @nitebone 3 года назад

    I get the 1004 error for '1. line of code stating, "This can't be applied to the selected range. Select a single cell in a range and try again."

  • @wayneedmondson1065
    @wayneedmondson1065 5 лет назад

    Hi Jon.. nice video on automating the deletion of rows based on cell values. I had not thought of using AutoFilter which is a great solution. As you know, I am a member of your VBA Pro course and so I got right to work thinking of a solution of my own. The trick I devised was to count from the bottom up, so you don't have to trap for skipping rows if deleting from the top down. The loop also ends when it hits the row header which makes it easy to adapt to different columns. Also, it works the same on a standard range and a formal Excel Table. The code follows below. As you can see, I am studying and learning your methods. Nice to have a new option using AutoFilter. I'll experiment with that too. Thanks again and Thumbs up!
    Sub DeleteProductRowsWithBlanks()
    Dim lRow As Long 'variable for last row
    Dim cRow As Long 'variable for current row
    Dim Counter As Long 'variable for counter of blank cells
    lRow = Cells(Rows.Count, 2).End(xlUp).Row 'get count of last row
    cRow = lRow 'set current row variable as last row - i.e. count from bottom up
    Counter = 0 'set blank cell counter to 0
    Application.ScreenUpdating = False 'disable screen updating for faster operation
    Do Until Cells(cRow, 5).Value = "Product" 'loop until reaching the column header of Product
    If Cells(cRow, 5).Value = "" Then 'test if current row in column 5 is blank
    Rows(cRow).EntireRow.Delete 'if blank, then delete entire row
    Counter = Counter + 1 'advance blank cell counter by 1
    End If
    cRow = cRow - 1 'move current row up by 1
    Loop 'loop and test again
    Beep 'when finished, alert user with BEEP and message box giving the number of deleted rows
    MsgBox "Procedure complete - " & Counter & " rows were deleted"
    Application.ScreenUpdating = True
    End Sub

    • @ExcelCampus
      @ExcelCampus  5 лет назад +1

      Hey Wayne,
      Thanks for sharing this alternate solution. You are correct with going backwards in the loop to delete rows. We cover that in the course as well, for anyone else that is wondering. If you loop forwards then the macro will likely encounter an error and/or delete rows at the end of the range, which might cause other problems.
      With the autofilter method presented in this video we don't have to worry about any of that. However, like Wayne mentioned, it's good to alternate techniques. The autofilter method works great for rows, but does not work for deleting columns based on conditions.
      Thanks again Wayne! I really appreciate your support! :-)

    • @wayneedmondson1065
      @wayneedmondson1065 5 лет назад

      Hi Jon.. thanks.. with your help (VBA Pro Course, your videos, your web site, etc.), I'm glad I now have the ability to contribute. And.. good points on the use of AutoFilter bypassing some of the issues involved with direct manipulation. There are so many ways to approach a problem. VBA unlocks the door to them all! In that regard, I've been experimenting with the use of Arrays and came up with the following for your example which would likely process faster on a very large data set (see revised code below). Thanks again for all the great resources you offer. Thumbs up!
      Sub DeleteProductRowsWithBlanksUsingAnArray()
      Dim arrProducts() As Variant
      Dim i As Long
      Dim c As Long
      arrProducts = Range("E1:E" & Cells(Rows.Count, 2).End(xlUp).Row)
      i = UBound(arrProducts)
      c = 0
      For i = UBound(arrProducts) To 4 Step -1
      If arrProducts(i, 1) = "" Then
      Cells(i, 5).EntireRow.Delete
      c = c + 1
      End If
      Next i
      Beep
      MsgBox "Procedure complete - " & c & " rows were deleted"
      End Sub

  • @kimbowman4063
    @kimbowman4063 3 года назад

    Running the macro when the column does not contain the lookup criteria an error on the delete rows section appears. How do you bypass this?

  • @jonsedman3416
    @jonsedman3416 2 года назад

    I am looking to have a macro button and when the button is pushed a user input box appears and then asks you what row on the excel sheet is to be deleted. Of course the workbook will have protection on so it will have to be turned off before the action happens and then restore after.. thanks Jon

  • @TheMuraleee
    @TheMuraleee 3 года назад

    Hello Brother, am getting debug on "Regular Range" Line no 3.. Can you plz help me to fix it

  • @james3603
    @james3603 3 года назад

    what if i have multiple criteria to delete , like if the status is closed, resolved, active, etc.?

  • @imapkru
    @imapkru 3 года назад

    Hi. Thank you for the video. I have criteria that lists several (22) tests in the test column. I want to delete everything but Spanish. Can I use "Spanish"? Or how would I list that in the criteria? It is a table.

    • @TheFall0fSummer
      @TheFall0fSummer 2 года назад

      a bit late and not the video poster, but yes you can use Criteria1:="Spanish"!

  • @darrenbonnar1504
    @darrenbonnar1504 Год назад

    How would I use VBA to Clear a range based on cell value, i.e If they use dropdown to display "Del" in a cell (B1) from that being changed I want the Range C1:Z1 to clear contents, Thanks

  • @1982degoel
    @1982degoel Год назад

    is it possible to delete one cell (not entire row )based on cell values ?

  • @abbisandi
    @abbisandi 5 лет назад +1

    Hi Jon great video - I need to run the reverse macro meaning...i want to delete all rows NOT Equal to a "Product 2" text name in the column. I would like to delete all rows that do NOT contain the name Product 2. I have tried using the in place of = in the macro but I get this error...."Compile error, expected named parameter." When I try to record a macro using filter to select all but name, I need I get another error called "too many line continuations." My tables are over 6000 lines long..Any ideas?

    • @greggowaffles
      @greggowaffles 5 лет назад

      hi abbisandi. were you ever able to solve this? i would love to help!

    • @yerzhankosbayev6436
      @yerzhankosbayev6436 3 года назад

      @@greggowaffles Criteria1:="=*text*"

  • @dinyarbuhariwalla1120
    @dinyarbuhariwalla1120 3 года назад

    I have a spreadsheet with almost more than 1000000 rows of data. I want to delete every 600th row so for eg i will start with starting from 1 - keep that data and delete the rest from 2 to 600. Next I will keep 601 and delete up to 1200. so basically increment of 600. What code should i use and how to delete?

  • @abbisandi
    @abbisandi 5 лет назад

    Jon - additionally - how would I get this macro to run on multiple sheets in a workbook but not ALL of the sheets. I would have to name the sheets in the code? What would the code look like?

    • @LoeblComServices
      @LoeblComServices 5 лет назад

      I don't mean to steal Jon's platform, but to help answer your question, you would have to loop all the worksheets in the workbook to exclude the worksheets you don't want the code to run on.

    • @alexhoward864
      @alexhoward864 5 лет назад

      bump, as I also need to know this. 3 months with no reply/answer?

    • @LoeblComServices
      @LoeblComServices 5 лет назад

      @@alexhoward864 What does your worksheet look like?

  • @tonywillingham8109
    @tonywillingham8109 2 года назад

    How do you prevent this method from always deleting the first row, which the Auto Filter will never hide?

  • @mnesevati
    @mnesevati 4 года назад

    There is a problem, for example: if you re-run the code again (value bases on table), an error will pop up!!!

  • @abbuthefame
    @abbuthefame 3 года назад

    If we want to find some content and delete .. if we don't know exact content

  • @keithbender1476
    @keithbender1476 4 года назад +1

    Attempting to delete rows with the word "Total" in a cell.

  • @harendrakumarsingh7699
    @harendrakumarsingh7699 8 месяцев назад

    Can we use it in Google sheets

    • @ExcelCampus
      @ExcelCampus  8 месяцев назад

      These VBA macros are based on Microsoft Excel. Google Sheets has its own coding language called App Scripts where you could do something similar.

    • @ExcelCampus
      @ExcelCampus  8 месяцев назад

      These VBA macros are based on Microsoft Excel. Google Sheets has its own coding language called App Scripts where you could do something similar.

  • @xblades1984
    @xblades1984 2 месяца назад

    And what if data exceeds row G1000 bro? Please always show something which gives permanent solutions and not temporary ones

  • @franktroplis
    @franktroplis 3 года назад

    Instead of using "" or "12/3/14", ... How can I do this using today's date? Example: Delete all rows that are older than today or yesterday.

    • @DerekElliott-qn2kz
      @DerekElliott-qn2kz 11 месяцев назад

      Frank did you ever figure this out? If I have rows in weekly buckets and I update the spread sheet, I want the macro to delete the rows that are older than the current date I add, how would I do that?

  • @HoangVu-yf1ix
    @HoangVu-yf1ix 5 лет назад +1

    I think we should clear filter before using auto filter for better result.

    • @ExcelCampus
      @ExcelCampus  5 лет назад

      Great point Hoang! I'll update the post and macro. Thanks! :-)

  • @vivaladavid550
    @vivaladavid550 4 года назад

    subscript out of range