Solved

What is the best way to have VBA count blank cells in a range?

Posted on 2010-08-31
19
517 Views
Last Modified: 2012-06-22
I have coded the following VBA to count blank cells in a range.  The cells contain formulas so i had to account for that but my code is too slow.

Column Q, R, S are phone numbers derived from trim operations and I am counting the cells without phone numbers.

Does anyone have a faster way to conduct this operation?


Dim MissingPhCt As Integer

Dim R as Integer



        Columns("T:V").Select

        Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

        

        Range("T2").Select

            For MissingPhCt = 1 To LastRow - 1

            R = MissingPhCt + 1

            

                ActiveCell.Offset(MissingPhCt - 1, 0) = WorksheetFunction.CountIf(Range(Cells(R, "Q"), Cells(R, "S")), "")

                  

            Next MissingPhCt

        

        Range("T1").Value = "Missing Phone #s"

        

        Range(Cells(1, 1), Cells(LastRow, LastCol + 3)).Select

        Selection.Copy

Open in new window

0
Comment
Question by:Tony_Rhoades
  • 7
  • 6
  • 4
  • +2
19 Comments
 
LVL 50

Expert Comment

by:Dave Brett
ID: 33572616
Your COUNTIF is quick - that isn't the problem

The slow part of your code is the loop dumping the formulas cell by cell

A much faster technique would be to write your formulas in a single range

Can you pls post an actual sample

Cheers

Dave
0
 
LVL 18

Expert Comment

by:Cory Vandenberg
ID: 33573855
As Dave suggested, get rid of the loop.

Replace this code:

            For MissingPhCt = 1 To LastRow - 1
            R = MissingPhCt + 1
           
                ActiveCell.Offset(MissingPhCt - 1, 0) = WorksheetFunction.CountIf(Range(Cells(R, "Q"), Cells(R, "S")), "")
                 
            Next MissingPhCt

With the snippet below.  I offer two solutions, one using copy/paste, one without it.  Can't test right now, so my apologies if one doesn't work.

Cheers,
WC
ActiveCell.Offset(1,0).Formula = "=COUNTIF(Q1,S1)"
ActiveCell.Offset(1,0).Resize(LastRow,)

'Or with copy/paste
ActiveCell.Offset(1,0).Formula = "=COUNTIF(Q1,S1)"
ActiveCell.Offset(1,0).Copy Destination:=Range(ActiveCell.Offset(1,0).Address,ActiveCell.Offset(LastRow,0).Address)

Open in new window

0
 
LVL 18

Expert Comment

by:Cory Vandenberg
ID: 33573862
Oh, and if you don't want to store formulas on the sheet, use the PasteSpecial
ActiveCell.Offset(1,0).Formula = "=COUNTIF(Q1,S1)"

ActiveCell.Offset(1,0).Copy 

Range(ActiveCell.Offset(1,0).Address,ActiveCell.Offset(LastRow,0).Address).PasteSpecial xlPasteValues

Open in new window

0
 
LVL 17

Accepted Solution

by:
calacuccia earned 500 total points
ID: 33574057
Also, don(t use ActiveCell, Activate or Select or Selection if you want quick & efficient

This should be much quicker with help of an array declared as variant at start of the procedure
Dim MissingPhCt As Integer

Dim R As Integer

Dim mArray As Variant

        

'LastRow = 142 --> This was not mentioned, just declared it for testing

        

Application.ScreenUpdating = False

Columns("T:V").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

mArray = Range("T2:T" & LastRow).Value

For MissingPhCt = 1 To LastRow - 1

    R = MissingPhCt + 1

    mArray(MissingPhCt, 1) = WorksheetFunction.CountIf(Range(Cells(R, "Q"), Cells(R, "S")), "")

Next MissingPhCt

Range("T2:T" & LastRow) = mArray

Range("T1").Value = "Missing Phone #s"

        

Range(Cells(1, 1), Cells(LastRow, LastCol + 3)).Select

Selection.Copy

Application.ScreenUpdating = True

Open in new window

0
 
LVL 17

Expert Comment

by:calacuccia
ID: 33575124
Range(Cells(1, 1), Cells(LastRow, LastCol + 3)).Copy is also better instead of lines 17/18 in the snippet above.
0
 
LVL 33

Expert Comment

by:Norie
ID: 33575745
And this might be an idea too?

Range("A1").Resize(LastRow, LastCol+3).Copy
0
 

Author Closing Comment

by:Tony_Rhoades
ID: 33577513
Thank you that works like a champ..  Also the added advice about using

Range(Cells(1,1), Cells(LastRow, LastCol +3)).copy

instead of .select and then selection.copy is much appreciated.  I will go back through all my code and clean this up as I imagine this simple change will improve the overall performace considerably.

Best Regards.
0
 
LVL 17

Expert Comment

by:calacuccia
ID: 33577598
Thanks for the grade & good luck :-)
0
 
LVL 18

Expert Comment

by:Cory Vandenberg
ID: 33578259
I'm a little confused.  Yes, removing Select statements will improve efficiency, but removing the looping procedure would do more for code efficiency.  You are simply repeating a formula.  There is no need to loop through a range to do that.

To each his own. Glad you found something you're happy with.

WC
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 17

Expert Comment

by:calacuccia
ID: 33578358
The improvement of my solution should not be the Select statements but the array operations and read/write operation of an array in one step.

But of course your solution should give tremendous improvement as well, I don't know which one would be quicker without have the real data: with your solution excel needs to calculate the formula's before being able to do the PasteSpeciaL
0
 
LVL 18

Expert Comment

by:Cory Vandenberg
ID: 33579397
Ok, adding an array is better (remvoing repetitive copy/pastes), but I'm guessing for a small range the difference between your solution and mine is negligible.  For a large range, I would have to imagine removing the loop altogether would produce more efficient code.

Cheers,
WC
0
 
LVL 17

Expert Comment

by:calacuccia
ID: 33580131
Hi WC,

You are right, this was a test with 40k rows.
Array operation took 1,46875 seconds
Paste/PasteSpecial operation took 0,53125 seconds

With 500 rows, the result is the same
Array operation took 0,015625 seconds
Paste/PasteSpecial operation took 0,015625 seconds

However, I had to rewrite your code a bit :-)

In case the question asker is interested, this worked:


Range("T2").Select

ActiveCell.Offset(0, 0).Formula = "=COUNTIF(Q2:S2,"""")"

ActiveCell.Offset(0, 0).Copy

Range(ActiveCell.Offset(0, 0).Address, ActiveCell.Offset(LastRow - 2, 0).Address).PasteSpecial xlPasteFormulas

Range(ActiveCell.Offset(0, 0).Address, ActiveCell.Offset(LastRow - 2, 0).Address).Copy

Range(ActiveCell.Offset(0, 0).Address, ActiveCell.Offset(LastRow - 2, 0).Address).PasteSpecial xlPasteValues

Open in new window

0
 
LVL 18

Expert Comment

by:Cory Vandenberg
ID: 33580406
calacuccia,

Ya, I wasn't certain the PasteSpecial xlPasteValues would work without first pasting the formulas.  It was late last night when I posted that.

If you are looking for truly efficient clean code, the following would be my best suggestion.

Cheers,
WC
Sub test()

    Dim rng As Range

    Dim LastRow As Long

    

    LastRow = 40000

    Set rng = Range("T2:T" & LastRow - 2)

    rng.Formula = "=COUNTIF(" & Cells(rng.Row, rng.Column - 3).Address(False, False) & ":" & Cells(rng.Row, rng.Column - 1).Address(False, False) & ","""")"

    rng.Copy

    rng.PasteSpecial xlPasteValues

End Sub

Open in new window

0
 
LVL 17

Expert Comment

by:calacuccia
ID: 33580461
Yep, it helps a bit :-) (40k rows)

Array operation took 1,484375 seconds
Paste/PasteSpecial operation took 0,53125 seconds
Efficient Paste/PasteSpecial operation took 0,515625 seconds
0
 
LVL 18

Expert Comment

by:Cory Vandenberg
ID: 33580601
:) I didn't just mean efficient in processing time, but also in typing the code and comprehending it later.

See ya around,
WC
0
 

Author Comment

by:Tony_Rhoades
ID: 33581054
Guys thank you for the continued interest in this question I have learned a lot.  I incorrectly assumed the array would be more efficent time wise.

I will however defer to the Clock and use WarCrimes  solution.  09/01/10 12:23 PM, ID: 33580406

Thanks Again.

Tony
0
 
LVL 18

Expert Comment

by:Cory Vandenberg
ID: 33581164
A range object in Excel is essentially an array, in the Object-Oriented sense of the word.

The difference in efficiency isn't that I'm not using an array, it's that I'm not using a loop.  In essence, I'm copying an array to an array when I write the Formulas, where as the accepted solution is merely writing one formula at a time to the array position, then copying the array.  This is where the lack of efficiency comes in and why we see a time discrepency on larger datasets but not smaller ones.

Cheers,
WC
0
 

Author Comment

by:Tony_Rhoades
ID: 33581280
Thank you for making this clear.  I will keep this in mind for the rest of my code.

Best

TR
0
 

Author Comment

by:Tony_Rhoades
ID: 33595681
I have posted a question about parsing my data and It now occurs to me that this conversation may apply.  

Would you all mind looking at question 09/01/10 01:48 PM, ID: 26445592 "Looking for a better way to parse my data?"
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A little background as to how I came to I design this code: Around 5 years ago I designed an add-in that formatted Excel files to a corporate standard, applying different cell colours and font type depending on whether the cells contained inputs,…
How to quickly and accurately populate Word documents with Excel data, charts and images (including Automated Bookmark generation) David Miller (dlmille) Synopsis In this article you’ll learn how to use ExcelToWord! to copy data,charts, shapes …
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now