Beyond Excel: VBA and Database Manipulation


February 24, 2011  6:53 PM

Solving Dynamic Ranges with Tables/ListObjects

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

Dynamic named ranges have been a subject of interest on Excel boards for sometime.  Lots of people want to know what’s the best way to create a named range that expands (or shrinks) according to the data entered, and can be used in formulas like VLOOKUP without change.  For some background on this subject see: Dynamic Ranges – Overcoming Shortcomings.  In that post I promised to talk about what I believe is truly, the one best way to handle this kind of thing, Excel’s Tables.

Tables!

In 2003, Excel introduced something called a “ListObject” also known as a “Table”.  There are several features packed into Tables, but the main feature of importance in this discussion is their ability to grow or shrink dynamically.  Out of the box, a table is a dynamic named range.  So why agonize over what formula best creates one?

Creating tables is easy, simply select any cell within the desired range of data and press Ctrl-L (in Excel 2007 or 2010 you can also use Ctrl-T).  Excel will probably guess correctly what range you meant but gives you the opportunity to specify exactly what you want.  Whenever your selected cell is in a table Excel adds the Table Tools tab to its ribbon. There you can change the table’s name using the convenient “Table Name:” box in the upper left corner.

Unlike formula approaches, tables don’t mind other tables on a worksheet.  And Tables come with right click menu functions for adding/inserting/deleting rows/columns.  As you add rows or columns, the table automatically encompasses the new data, extends formats and formulas, and when rows are inserted, moves tables below to make room. 

Tables are superior to named ranges in every way except one: they can’t be used as datasources.   That’s easily overcome.  Simply select the range you want to use as a datasource (that can be the entire table, just the data, a column…) and give it a name using the name box in the upper left corner of each worksheet, or using the name manager.  The new name is every bit as dynamic as the best dynamic range formula – without the formula.

It’s Time to Move Ahead

At the time of this blog post, I still meet Excel fans enthusiastic over dynamic ranges.  When asked “why not tables?” I usually get a blank stare.  Some point out tables don’t work with all versions of Excel.  True enough.  But it’s been almost a decade now since XL 2003 came out.  I’ve long since upgraded every user in the company I work for to Office 2003 or higher.  I’ll bet your company has too.  So put your favorite dynamic named range formula in a frame and hang it on the wall with other momentous from your past.  It’s time to move ahead with tables.

January 27, 2011  9:50 AM

Animating Your Company’s Logo in Excel

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

This post shows how to animate a logo in Excel using VBA.  (Click here to download code)

Preview:
[kml_flashembed movie="http://www.youtube.com/v/97tZL3TJhWs" width="480" height="292" wmode="transparent" /]

Logos are an easy way to add a sense of professionalism to your work. Splash screens and logos are part of every software product purchased and should be part of every application you provide you customers. Besides, animating logos is fun. It entertains users and sets your work apart from the average Excel programmer.  I use them when the workbook first opens.  Here’s how it’s done.

Open a blank workbook. Rename the first tab “Data”. This will be the worksheet displayed when our workbook opens.  Now get a copy of your company’s logo. Your company’s website probably has one about the right size. Paste it onto the Data worksheet.  We need to name it “Logo”. To do that, select it, then use Alt-F11 to get to the Visual Basic Editor. Use Ctrl-G to display the Immediate Window. Type “Selection.Name = “Logo” and hit enter. Now we’re ready to code.

Use Ctrl-R to bring up the Project Explorer. Double click “ThisWorkBook.” That brings up the workbook’s code window.  Our first routine must run when the workbook opens so we will code it in the Workbook_Open event. This routine activates the worksheet we renamed “Data”, and passes our “Logo” shape to two routines. The first “Grows” the logo into view. The second spins it once.

Private Sub Workbook_Open()
 
    Worksheets("Data").Activate
    ActiveSheet.Shapes("Logo").LockAspectRatio = False
    GrowShape ActiveSheet.Shapes("Logo"), 10
    SpinShape ActiveSheet.Shapes("Logo"), 10
           
End Sub

The “Grow” routine expands any shape into view. It first turns off screen updating. This allows us to make changes behind the scenes and display the results when we’re ready. Next, the routine remembers the shape’s dimensions. Then the routine changes the shape’s size, displays it, freezes the screen, and loops back until finished. Before returning, the Grow routine makes sure the shape is exactly as we found it.

The Spin routine is nearly identical. It freezes the screen, remembers the shape’s original dimensions, then alters the shapes size in a loop that simulates the shape spinning around its Y axis. When finished, the routine restores the shape to its original size.

That’s all there is to animating a logo. 

Function GrowShape(ByRef Shape As Shape, Step As Integer) As Boolean
'   Description:Expands a shape into view
'   Parameters: Shape       The shape to animate
'               Step        Larger #s animate faster
'   Example:    GrowShape ActiveSheet.Shapes("Logo"), 10
'   Note:       For best results, shape should be hidden before calling
'               this routine
'     Date   Init Modification
'   01/10/11 CWH  Initial Programming
    Dim lCenterX As Long    'Shape's center X coordinate
    Dim lCenterY As Long    'Shape's center Y coordiante
    Dim lWidth   As Long    'Shape's width
    Dim lHeight  As Long    'Shape's height
    Dim l        As Long    'Generic Counter for the loop
   
    Application.ScreenUpdating = False
   
    With Shape
       'Remember shape's original dimensions
        lCenterX = .Width / 2 + .Left
        lCenterY = .Height / 2 + .Top
        lWidth = .Width
        lHeight = .Height
       'Animation Loop
        For l = 0 To lWidth Step Step
            .Width = l
            .Height = l * lHeight / lWidth
            .Left = lCenterX - .Width / 2
            .Top = lCenterY - .Height / 2
            Shape.Visible = True
            Application.ScreenUpdating = True
            Application.ScreenUpdating = False
        Next l
       'Restore shape's original dimensions
        .Width = lWidth
        .Height = lHeight
        .Left = lCenterX - .Width / 2
        .Top = lCenterY - .Height / 2
    End With
   
    Application.ScreenUpdating = True
End Function
 
Function SpinShape(ByRef Shape As Shape, Step As Integer) As Boolean
'   Description:Expands a shape into view
'   Parameters: Shape       The shape to animate
'               Step        Larger #s animate faster
'                           Steps should divide 90 evenly
'   Example:    SpinShape ActiveSheet.Shapes("Logo"), 10
'     Date   Init Modification
'   01/10/11 CWH  Initial Programming
   
    Const Pi = 3.14159265358979
    Dim sng01 As Single     '1 Degree in Radians
        sng01 = Pi / 180
       
    Dim lCenterX As Long    'Shape's center X coordinate
    Dim lCenterY As Long    'Shape's center Y coordiante
    Dim lWidth   As Long    'Shape's width
    Dim lHeight  As Long    'Shape's height
    Dim l        As Long    'Generic Counter for the loop
   
    Application.ScreenUpdating = False
   
    With Shape
        .LockAspectRatio = False
       'Remember shape's original dimensions
        lCenterX = .Width / 2 + .Left
        lCenterY = .Height / 2 + .Top
        lWidth = .Width
        lHeight = .Height
       'Animation Loop
        For l = 0 To 360 Step Step
            .Width = lWidth * Abs(Cos(l * sng01))
            .Left = lCenterX - .Width / 2
            If l = 90 Or l = 270 Then .Flip msoFlipHorizontal
            Shape.Visible = True
            Application.ScreenUpdating = True
            Application.ScreenUpdating = False
        Next l
       'Restore shape's original dimensions
        .Width = lWidth
        .Height = lHeight
        .Left = lCenterX - .Width / 2
        .Top = lCenterY - .Height / 2
    End With
   
    Application.ScreenUpdating = True
End Function


January 18, 2011  5:28 PM

Debug Your Data with Conditional Formatting

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

(By Guest blogger Yoav Ezer)

Many times when a workbook is crammed full of numbers, your data can be difficult to read. This is bad enough when you are sure the data is correct, but If you are supplied a spreadsheet that contains potential errors you really want to be able to detect them so they can be fixed.

A common error in inputting is where your work contains duplicate records. There are a couple of ways we can delete duplicates, but what if you only want to see them rather than delete them? Here is when conditional formatting can help. With this little technique you can make the duplicates jump out at you!

Check out this screen grab below.

See how the duplicate rows are highlighted? In this sheet, the highlighting helps us indentify duplicate invoices.

The Solution

Here is how it was done.

First you need to go to the conditional formatting dialog as you normally would.

Then in the “Edit the Rule Description” box:

Enter this formula:

=SUMPRODUCT(($B2=$B$2:$B$16)*($A2=$A$2:$A$16)*($C2=$C$2:$C$16))>1

The formula might look complicated, and it kind of is. It relies on a function you might not have seen much called SUMPRODUCT. If you are curious about the function, this article is a great introduction to the topic.

In this formula, SUMPRODUCT will return the sum of rows from rows 2 through 16 where columns A,B and C are equal to the current row. If the result is greater than 1 then the format is implemented on that row.

Summary

As you can see, when you are given a spreadsheet containing problems, you don’t always want to nuke error rows, some times you need to know about them so you can deal with the issues at source. Conditional formatting can raise your awareness without changing the content of your spreadsheet. Give it a try!

About the author

Yoav Ezer co-authors the technology and productivity blog Codswallop. He is also the CEO of a company that produces PDF to Excel conversion software.

For more Excel tips from Yoav, join him on Facebook or Twitter


January 13, 2011  2:00 PM

Dynamic Named Ranges in Excel – Overcoming Shortcomings

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

A couple of months ago, Guest blogger Yoav Ezer posted a piece including the concept of Dynamic Named Ranges (see Strategies for Speeding Spreadsheets).  Dynamic Named Ranges are ranges within Excel that have been named using “Name Manager” or “Define Name” and that can be expanded or contracted without having to change what the name refers to.  Once named, you can use the range’s name in formulas and data validation instead of the common “$A$1:$D$50″ cell references.  This makes your formulas simpler to read.  And with the dynamic nature of Dynamic Named Ranges, you don’t have to change the formula when rows of data are added. 

Here is a typical formula that could be added in Name Manger for a named range that starts in cell $A$1, has two columns, and can grow to as many rows as entries:

=OFFSET($A$1,0,0,COUNTA($A:$A),2)

Translating this formula for us humans, it says:

  • From $A$1
  • Go down 0 rows
  • Go right 0 columns
  • Expand to down by the number of cells in column A that contain characters
  • Expand to the right 2 columns 

Shortcommings

I “Googled” the subject and found many articles on Dynamic Named Ranges.  Obviously there is a lot of interest and many examples of their use; however, in every article I read, including those in Microsoft’s MSDN, I kept coming across the same shortcomings:

  • If your range contains empty cells, especially in the first column, you’re likely to get bad results
  • If your range contains spaces after the last row, you’re likely to get bad results.
  • If your range contains columns of different lengths, the suggested approaches are very cumbersome.
  • If your range starts somewhere other than row 1, the formula gets more complex.
  • If another range exists below or to the right of the first named range, you’re likely to get bad results.

Most of these limitations are because almost everyone seems to want to use COUNT or COUNTA to determine how many rows should be contained in the range.  I found one blogger who used MATCH instead of COUNT.  This had the advantage of skipping over empty cells, but still worked only for numbers, or for characters, but not for both (unless you double the formula and the MAX function). 

=OFFSET($A$1,0,0,MATCH("",$A:$A,-1),2)		'Finds last character cell
=OFFSET($A$1,0,0,MATCH(1E+306,$A:$A,1),2)	'Finds last numeric cell

Seeking A Better Approach

The above approaches all work.  But no one of them works for all circumstances by itself.  And none of the approaches dealt with the stray space after the table’s last row.  That’s not good enough.  I want one compact formula that requires as little thought as possble that works for as many situations as possible.  In researching and experimenting, I accidently stumbled on a quirk regarding formulas stored in names that makes overcoming these problems much simpler.  Chip explains this quirk very well.

Defined Name Formulas And Array Formulas by Charles H. Pearson

If you use a formula in a Defined Name, that formula is evaluated as if it were an array formula. There is no way to force a formula in a Defined Name to be evaluated as a non-array formula.

Brilliant!  With this bit of knowledge, we can use logical functions that are insensitive to the type of data used (Numbers vs Characters).  Here is an array formula that finds the last row in column A containing anything at all (NOTE! The curly brackets are the result of Shift-Ctrl-Enter.  For more information on how to enter array formulas see Array Formulas by Charles H. Pearson).

{=MAX(IF($A:$A<>"", ROW($A:$A),0))}

Building on this, we can find the last row within the first four columns that contains anything at all, regardless of which column is longest.

{=MAX(IF($A:$D<>"", ROW($A:$A),0))}

Because logical operators in Excel return 0 for FALSE and 1 for TRUE, we can shorten the formula up a bit, if that’s your preference.

{=MAX(($A:$D<>"")*ROW($A:$A))}

But one problem remains.  In my opinion, entries containing only spaces are the same as totally empty cells and as I said before, the above formula finds cells that contain anything at all, including those with just spaces.  No worries, this is simple enough to overcome by trimming cells.

{=MAX((TRIM($A:$D)<>"")*ROW($A:$A))}

This formula finds the last cell that contains anything other than just spaces.  It doesn’t matter if any of the cells in between are empty.  It doesn’t matter if any of the cells are numbers or characters.  It doesn’t matter which column is longest. To put it all together, you need to adjust for one more thing, the starting row.  I often want my ranges to start in row 4 with totals in row 2.  So if you want your range to start somewhere other than row 1, you need to subtract the starting row number and add 1 back for good measure.   Here is the final formula that you would enter into Name Manager for a range that starts in $A:$4 and has 5 columns (NOTE! Name Manager does not need the curly brackets since it treats ALL formulas as array formulas no matter what).

=OFFSET($A$4,0,0,MAX((TRIM($A:$E)<>"")*(ROW($A:$A)))-3, 5) 

This works.  It’s also slow.  It’s cumbersome.   

Solving with VBA

Formula approaches just don’t work well. There are just too many ways they can fail and too many limitations.  So I looked to VBA.  VBA has always had a very simple and elegant way of dealing with dynamic ranges:

Set DynamicRange = Range("A4").CurrentRegion

CurrentRegion finds all adjacent non-empty cells.  So if “A4″ is anywhere inside a table, CurrentRegion will identify the entire table.  One minor problem is it will also pick up any adjacent cells with stray spaces.  But a bigger problem is that when used in a UDF (User Defined Function intended to be used within an Excel formula), CurrentRegion returns only one cell. 

A different approach (copied from Andy Pope) can be encapsulated into a VBA routine and used in a UDF context:

Set DynamicRange = Range("A4").Resize(Range("A4").End(xlDown).Row - 1, _
                   Range("A4").End(xlToRight).column - 1)

End() works as long as there is more than one row and column in the range.  If, for example, only one row is in the table, the End() method will find the last cell in the worksheet or the next list.

The “One Best Way”

Going through this exercise was interesting, but utlimately, neither VBA, nor complex formulas are required to create dynamic ranges without ANY of the shortcommings of either.  We’ll discuss that after another great Excel tip from Yoav Ezer.


October 4, 2010  12:58 PM

Chart Drill Down

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

PivotChart Drill DownThis seems so basic to me that I was not surprised Googling “Drilldown Excel Chart” shows lots of interest out there.  But the implementation is so simple that I was very surprised Googling “Drill Down Excel Chart” yielded almost no good suggestions.  That ends today.

Preview:
[kml_flashembed movie="http://www.youtube.com/v/-Uu2WqDxLdk" width="480" height="292" wmode="transparent" /]

For beginners: What is “Drilldown?” 
Drilldown is displaying underlying details for a total.  This is important because we hope charts and summaries show something we didn’t know and/or expect.  When that happens, we want to know why.  Displaying what makes up a total helps answer that question.

Doesn’t Excel Support Drilldown Automatically?
In PivotTables and Outline Reports – yes.  You can double click any calculated number in these Excel objects and Excel displays the associated rows from their source data range.  But if you double click on a Chart/Graph element, the “Format Data Point” dialog box appears.  That’s not what my users want.  The good news, though, is the very same mechanism that reveals detail beneath PivotTables makes coding drilldown for PivotCharts a snap.

What are PivotCharts?
A PivotChart is a chart over a PivotTable.  In the templates provided in this blog, we use PivotTables to summarize data in our extracted rows.  PivotTables are extremely flexible and allow the user to slice and dice data in many, many useful ways.  The only draw back to PivotTables is they show numbers, not graphs.  This is easily overcome by simply creating a chart over the PivotTable.  Charts made from PivotTable data, as opposed to simple rows of data, also allow users to slice and dice the underlying data just like the user can with a PivotTable.  The only drawback to the PivotChart is that it lacks Drill Down. 

Adding Drilldown to PivotTable Charts
This “trick” only works with PivotCharts because it relies on the PivotTable’s ShowDetail property.  As mentioned before, you can double click on any calculated result in a PivotTable and it will automatically show the associated detail rows.  If you start the Macro Recorder, double click on a PivotTable cell, stop the recorder, and then view the recorded code, you’ll see something like this:

Range("B9").Select
Selection.ShowDetail = True

…where “B9″ is the cell you double clicked.  The Selection.ShowDetail = True is what causes the detail to display.  Now when you create a PivotChart from a PivotTable, each PivotTable cell becomes a chart element.  So what we have to do is figure out which chart element the user double clicked and which PivotTable cell that represents.  Then all that’s left to do is use that cell’s ShowDetail property to display the data.  As it turns out, this is almost easier done than said.

Determining Which Chart Element was Clicked
Excel provides a simple routine that makes this easy – ActiveChart.GetChartElementActiveChart.GetChartElement is a method attached to every chart in Excel.  You pass to it the mouse pointer’s X and Y coordinates and it returns the Chart Element Type and two of that Chart Element Type’s properties.  Chart Element Types can be the chart’s Title, Legend, Axis, … or a Graph Element.  We are only interested in Graph Elements such as a slice in a Pie Chart, a line in a Line Chart, a bar in a Bar Chart, etc.  So if ActiveChart.GetChartElement returns anything other than a Chart Element Type of 3 (Graph Element), we know to ignore things and move on.  On the other hand, if the user clicked a Graph Element, we want to show the detail.  When Chart Element Type is 3, Arg1 is the associated PivotTable row and Arg2 is the column.  So to show the detail beneath we use:

ActiveChart.PivotLayout.PivotTable.DataBodyRange. _
            Cells(Arg2, Arg1).ShowDetail = True 

Capturing Chart Double Click and Mouse Pointer’s X and Y
Every Chart also has a Chart_MouseUp event.  Chart_MouseUp fires whenever the user clicks (and releases) the mouse on a chart.  Excel also passes a few properties to this event.  Two are important to us: X and Y.

We now have all of the pieces to the puzzle.  All that’s left to do is put it together.  Place this code in the Chart Sheet object:

 

Private Sub Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, _
                          ByVal x As Long, ByVal y As Long)
'   Description:Drill Down into Pivot Chart's data
'   Parameters: Button  Mouse botton that was released
'               Shift   State of SHIFT, CTRL, and ALT keys
'               x       Mouse pointer X coordinate within Chart
'               y       Mouse pointer Y coordinate within Chart
'   Example:    *none - This is an event handler
'     Date   Init Modification
'   10/04/10 CWH  Initial Programming 
    On Error GoTo ErrHandler
   
    Dim ElementID As Long
    Dim Arg1 As Long
    Dim Arg2 As Long
       
'   Pass: x, y. Receive: ElementID, Arg1, Arg2
    ActiveChart.GetChartElement x, y, ElementID, Arg1, Arg2
   
'   If data element clicked, show detail
    If ElementID = 3 Then
        ActiveChart.PivotLayout.PivotTable.DataBodyRange. _
            Cells(Arg2, Arg1).ShowDetail = True
        ActiveSheet.Cells(2, 2).Select
        ActiveWindow.FreezePanes = True
    End If
ErrHandler:
   
    If Err.Number <> 0 Then MsgBox _
        "Chart_MouseUp - Error#" & Err.Number & vbCrLf & _
        Err.Description, vbCritical, "Error", Err.HelpFile, Err.HelpContext
    On Error Resume Next
    On Error GoTo 0
   
End Sub


September 23, 2010  7:45 PM

Controlling the Cursor: Find_Unlocked_Cell

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

This post has been superseded. Please see: http://itknowledgeexchange.techtarget.com/beyond-excel/excel-data-entry-protection-solution/


September 14, 2010  8:02 PM

Controlling the Cursor: Position_Curosr_In_Data

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

This post has been superseded. Please see: http://itknowledgeexchange.techtarget.com/beyond-excel/excel-data-entry-protection-solution/


September 8, 2010  5:49 PM

Back to Controlling the Cursor

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

This post has been superseded. Please see: http://itknowledgeexchange.techtarget.com/beyond-excel/excel-data-entry-protection-solution/


August 31, 2010  10:16 AM

Strategies for Speeding Spreadsheets

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

By guest contributor: Yoav Ezer

NOTE: This post provides an example spreadsheet: accelerating-excel.xlsm.  Due to concern for your system’s security, macro enabled spreadsheets cannot be stored in this blog.  So to accomodate security and free exchange of ideas, we loaded the spreadsheet as a text file with a “txt” extension.  To use this example, right click the link, select “Save Target As”, change the extension on the file name from .zip (it’s a text file that ITKnowledgeExchange has compressed for you) to .xlsm, click “Save”, scan your local copy for viruses, then open it.

Do your Excel spreadsheets sometimes take too long to calculate? It may be due to formulas that crunch large sets of data (for example, data that comes from large databases – the focus of this blog). This is because Excel recalculates all formulas that depend on a specific cell every time you change that cell. And if those formulas have dependents, Excel will recalculate them, and their dependents, and so on, and so on.

Consider the formula =SUM(A:A). This adds all cells in column A. It recalculates each time you update any cell in column A. Fortunately, the SUM function is very fast and may not cause significant delay even if used a 1,000 times in your workbook. But more advanced functions, like SUMPRODUCT() and array formulas, are not so efficient.

For instance, the following array formula is pretty simple: =SUM(IF(MOD(A:A,2)=1,A:A,0)). It sums all odd numbers in column A. It is much slower than the SUM function. I’ve used this formula only 12 times on sheet1 (See accelerating-excel.xlsm above) in this workbook and on my machine it takes 5 seconds to add a value to column A, which makes this workbook too slow to use.  Fortunately for us, there are ways to make Excel work faster even with advanced formulas.

Strategy #1: Use Limited Ranges
The reason the array formula evaluates so slowly is that it calculates for every cell in column A (that’s more than 1 million cells). One way to make this formula work faster is to limit the range. So instead of using this formula:

{=SUM(IF(MOD(A:A,2)=1,A:A,0))}

We can use this formula specifying only the rows needed:

{=SUM(IF(MOD(A1:A10000,2)=1,A1:A10000,0))}

NOTE: Excel adds curly brackets when you enter a formula using CTRL+SHIFT+ENTER. CTRL+SHIFT+ENTER tells Excel your formula is an array formula. For more information on array formulas and their power, see: Introducing Array Formulas in Excel by Colin Wilcox and John Walkenbach

Because the revised formula is limited to 10,000 rows it works 100x times faster!

Strategy #2: Use Dynamic Ranges
Strategy #1 works as long as you know how many cells contain data. When you don’t know, you can still limit your ranges using a Dynamic Range. Dynamic Ranges expand automatically to include only cells that contain data.  You can define a dynamic range called ‘ColumnA’ like this:

=OFFSET(Sheet2!$A$1,0,0,COUNT(Sheet2!$A:$A),1)

And then use it in the original formula in the following manner:

{=SUM(IF(MOD(ColumnA,2)=1,ColumnA,0))}

NOTE: See How to Set up a Named Range in Microsoft Excel if you need help with this.

This formula calculates only rows in column A that contain data. That’s good for two reasons: It reduces the number of cells calculated if your range contains fewer cells than anticipated; AND, it calculates cells that might otherwise be overlooked if your range contains more cells than anticipated. For more information on Dynamic Ranges see: Introduction to Dynamic Ranges.

To experience the performance difference between these two methods, open the sample file and update data on the first and second sheet. You’ll see a very palpable difference.

Strategy #3: Stopping/Starting Calculation
At times, even limiting the range used in the formula isn’t enough. One of our clients had a workbook with over 12,000 array formulas and although we used dynamic ranges to limit the range size in each of those formulas, the workbook took over a minute to update with 1,000 data rows. For that client we used the following technique.

The workbook was divided into a data entry sheet and ‘data analysis’ sheets which contained the array formulas. We employed a simple macro to stop the formulas on the workbook from automatically updating every time the user entered the ‘data entry’ sheet and a second macro to calculate all the formulas on the workbook when the user left the ‘data entry’ sheet. This way the user was able to update data very quickly and wait only once (when leaving the sheet).  Here is the macro we used whenever the user entered the ‘data entry’ sheet:

Private Sub Worksheet_Activate()
Application.Calculation = xlCalculationManual
End Sub

And this is the macro we used when the user left the sheet:

Private Sub Worksheet_Deactivate()
Application.Calculate
Application.Calculation = xlCalculationAutomatic
End Sub

You can see how stopping and starting the automatic calculations effects performance in the sample file.

Summary
We use Microsoft Excel to improve productivity. We can improve productivity even more by removing unnecessary waits through writing efficient formulas and controlling when Excel does its magic! Look for opportunities to use these techniques to speed results and improve the user experience.

Do you have Excel optimization tips? Please share with us in the comments.

About the author
Yoav Ezer co-authors the technology and productivity blog Codswallop. He is CEO of Cogniview, producer of PDF2XL, a Native PDF to Excel Converter, PDF2XL OCR, a scanned PDF to Excel converter, and PDF2XL Enterprise, a universal format converter to Excel.  For more Excel tips from Yoav, join him on: Facebook; or Twitter

Thanks Yoav for those great tips!


August 21, 2010  7:47 PM

Controlling the Cursor

Craig Hatmaker Craig Hatmaker Profile: Craig Hatmaker

This post has been superseded. Please see: http://itknowledgeexchange.techtarget.com/beyond-excel/excel-data-entry-protection-solution/


Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: