VBA - Filtering Data

It's a common mistake when we start using VBA to filter data by using long loops and conditions. This is probably the most logical way to interpret what we want to do. When we use loops and conditions we are taking to the code our natural process of filtering data. LOOK LINE BY LINE, AND IF A CONDITION IS MET, TAKE ACTION. Well yes, that works but it's not the optimal solution. Loops are great, I love them, but they are evil! They can slow down your process a lot when your data is considered big.

Fortunately, we have a better "not that naturally logical" way to do it. FILTER! Like water and oil you can separate values and once you have them visible, take the desired action. Let's see it on the code:





Ok, this wasn't that complicated. Let's see what we are doing here:
1- I'm selecting the Data that I want to filter.
2- I'm applying a filter to the 5th column of my Data, based on the Criteria "Bikes".
3- My Range shows now all those rows where "Bikes" is a parameter.
4- I'm selecting everything that's visible and deleting the Entire Row.
Here note the Offset(1) after rData. This is just to not consider the first Row where the headers are positioned.
5- I'm removing the Filter so sheet goes back to normal.


This way we avoid looping through 100K lines of rows when we only want to delete 50. See the difference? HOWEVER, not everything is sweet about this method;  what happens when your filter still shows 10K rows pending to delete? Yes, Excel takes 10 to 15 mins to delete the chunk of data. Why? Well here is why: Excel is very Tragic. Nah, not really, but since your data isn't organized (sort), Excel will have to delete the chunks of intercalated data and reorganized so it doesn't leave empty rows between them. If you are deleting 10K lines and these lines are all separated that means that excel will have to group the empty rows 10K times. Meaning more work. So, the solution:

Group all the Data you want to delete together and Excel will only have to group the empty rows once. Simple enough…. Look for the added code below.




Just a final advice: don't make rigid Procedures. What do I mean? This last procedure that I showed only works to delete rows in the Activesheet, 5th Column (E) and Bikes. Make it dynamical by passing these conditions as parameters in your procedure.


That's all folks... Cheers!

Comments

Popular posts from this blog

VBA - Using JSON in VBA

VBA - Copy Sheet from One Workbook to Another

VBA - Change IF Statements for Reference Table