Solved

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

Posted on 2010-08-31
19
503 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
Comment Utility
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:WarCrimes
Comment Utility
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:WarCrimes
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
And this might be an idea too?

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

Author Closing Comment

by:Tony_Rhoades
Comment Utility
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
Comment Utility
Thanks for the grade & good luck :-)
0
 
LVL 18

Expert Comment

by:WarCrimes
Comment Utility
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 17

Expert Comment

by:calacuccia
Comment Utility
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:WarCrimes
Comment Utility
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
Comment Utility
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:WarCrimes
Comment Utility
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
Comment Utility
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:WarCrimes
Comment Utility
:) 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
Comment Utility
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:WarCrimes
Comment Utility
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
Comment Utility
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
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Workbook link problems after copying tabs to a new workbook? David Miller (dlmille) Intro Have you either copied sheets to a new workbook, and after having saved and opened that workbook, you find that there are links back to the original sou…
This Micro Tutorial demonstrates how to create Excel charts: column, area, line, bar, and scatter charts. Formatting tips are provided as well.
This Micro Tutorial will demonstrate how to use a scrolling table in Microsoft Excel using the INDEX function.

763 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

7 Experts available now in Live!

Get 1:1 Help Now