cellMatrix.net
Spreadsheet Modeling and Related Topics

About

Formulas, Charts, and Models Created with Microsoft Excel.
More . . .

Statistics

  • Total Entries - 102
  • Current Viewers - 10

Categories

Recent Comments

Syndicate

Validate

Building the Formula Trace Tool Post 3

In the final post of this series, I've completed the first version of the formula trace tool by adding the following:

  • The option to trace dependent cells.
  • A "Step" function that allows the user to move through precedent or dependent cell references. It reactivates the tool from any precedent or dependent cell reference.
  • A "Clear" function that allows the user to clear the audit arrows without closing the tool.
  • A command button to activate the tool. The command button symbol is a blue arrow pointing to the right over a white background.

The first version of the tool looks like this:

image

The tool can be used as a regular spreadsheet file (.xls) or as an add-in (.xla). To use as a spreadsheet file, open TraceTool.xls as you would any other spreadsheet. The command button with the blue arrow should appear. Then open the spreadsheet that you want to audit. To use the tool as an addin, open TraceTool.xls and then save it as TraceTool.xla.

You can download the utility via the link below:

To activate the tool, click on the command button:

image

Building the Formula Trace Tool Post 2

As a recap to Building the Formula Trace Tool Post 1, a macro was created that records the cell address and worksheet name for each precedent cell based on the active cell address. Each precedent cell address and worksheet name are then converted into a test string and then loaded into an array.

The next steps are to load the results of the array into a listbox. To do so, first I created a userform that contains a listbox (shown below in the design view). The userform is called "frmTrace" and the listbox within that userform is called "Listbox1". I've also added a command button (Exit) to right side bottom of the userform called "btnExit".

image

After creating the userform, I added the following code to the code module to initialize it.

Private Sub UserForm_Initialize()

    Application.ScreenUpdating = False

    frmTrace.StartUpPosition = Manual
    frmTrace.Top = 50
    frmTrace.Left = 500

    Call TracePrecedents

    Application.ScreenUpdating = True

End Sub

To show the userform I added a command button to the worksheet. That command button is named "CB1" and captioned "Trace Formulas". I added the following code to the command button to show the userform.

Private Sub CB1_Click()
    frmTrace.Show
End Sub

When the userform is initialized, it calls a procedure called "TracePrecedents". The TracePrecedents procedure is what was originally presented in Building the Formula Auditing Tool Post 1. After some more work, that procedure has been modified to the one below and added to the "frmTrace" code module.

Private Sub TracePrecedents()

    On Error Resume Next

    Dim iAddress As String
    Dim UniqueValues As New Collection
    Dim iArrow As Integer

    Set Origin = ActiveCell

    Origin.ShowPrecedents

    For iArrow = 1 To 200

        For iLink = 1 To 200

            Err = 0

            Set oPrec = Origin.NavigateArrow(True, iArrow, iLink)

            Cell = oPrec.Address
            Sheet = oPrec.Parent.Name
            Workbook = oPrec.Parent.Parent.Name
            iAddress = "[" & Workbook & "]" & Sheet & "!" & Cell
            UniqueValues.Add iAddress, CStr(iAddress)

            If Err <> 0 Then Exit For

        Next

    Next

    frmTrace.ListBox1.RowSource = ""
    For Each Item In UniqueValues
        frmTrace.ListBox1.AddItem Item
    Next Item

End Sub

At this point the cell references will load into the listbox. However, code still needs to be added that programs the listbox to respond when a cell reference is activated. The procedure below parses the text string into a workbook, worksheet, and cell reference component. Each time the list box is clicked, the event fires.

Private Sub ListBox1_Click()

    Dim iSeg1, iSeg2 As Integer
    Dim iCell, iSheet, iWorkbook As String

    Item = ListBox1.Value

    iSeg1 = Application.WorksheetFunction.Find("]", Item)
    For i = 1 To Len(Item)
        iWorkbook = Mid(Item, 2, iSeg1 - 2)
    Next i

    iSeg2 = Application.WorksheetFunction.Find("!", Item)
    For i = 1 To Len(Item)
        iCell = Mid(Item, iSeg2 + 1, i)
    Next i

    For i = 1 To Len(Item)
        iSheet = Mid(Item, Len(iWorkbook) + 3, Len(Item) _
        - Len(iWorkbook) - Len(iCell) - 3)
    Next i

    Workbooks(iWorkbook).Activate
    Worksheets(iSheet).Select
    Range(iCell).Select

End Sub

In the screenshot below, I've activated the userform by hitting the Trace Formulas button. The active cell is C21 as indicated by the blue background for the cell reference "[TraceTool.xls]Sheet1!$C$21" in the userform. The precedent references for cell C21 are indicated by the blue tracer arrows and are loaded as a list in the userform. As I click on each cell reference in the userform, that cell reference will be selected via the click event shown above.

image

Finally, I've added code to exit the userform and clear the auditing arrows. The procedure below fires when the Exit button is clicked.

Private Sub btnExit_Click()
    ActiveSheet.ClearArrows
    Unload Me
End Sub

The procedure below fires if the userform is terminated in a way other than using the Exit button.

Private Sub UserForm_Terminate()
    ActiveSheet.ClearArrows
End Sub

In the next post I plan to add code to trace dependent cells and possibly add a feature that allows the user to step through formulas.

References:
  • John Walkenbach's book titled Excel 2003 Power Programming with VBA - Part IV - served as a reference for how to create the userform, listbox, and command button for the Trace Tool add-in.

Align Charts to Worksheet Grid Via Chart Names

In the previous post, I presented a macro that aligned embedded charts to a worksheet cell grid given certain criteria. The macro works OK if you're not concerned about the order in which any chart is placed on the worksheet. Andy Pope offered a more efficient version via comment. However, after more review I found that the macro would rearrange the original placement of one or more of the charts if one or more of the original charts were deleted and replaced. The root of the problem is that embedded charts are really shapes that are stored with an index number in the shapes collection. If a shape is deleted and a new shape created, the new shape is given the last index number in the collection. To place individual charts where you want, you need to somehow specify what index number of the shape you want to where.

The only way I could think of to get around this problem was to name each chart individually and the order the charts by name. Depending on how I wanted the charts to fall on the worksheet, I named each chart "Cht1", "Cht2", "Cht3", etc. I then modified Andy's macro to order the charts by the chart names:

Sub AlignCharts()

    Dim Cht As ChartObject
    Dim ChartsAcross As Integer
    Dim ColumnsAcross As Integer
    Dim RowsDown As Integer
    Dim Rng1 As Range
    Dim Rng2 As Range

    Set Rng1 = Range("B2")
    ChartsAcross = 3
    ColumnsAcross = 4
    RowsDown = 10

    Set Rng2 = Rng1
    
    TotalCharts = 0
    
    For Each Cht In ActiveSheet.ChartObjects
        TotalCharts = TotalCharts + 1
    Next Cht
    
    For Cnt = 1 To TotalCharts
    
    Set Cht = ActiveSheet.ChartObjects("Cht" & Cnt)
        With Cht
            .Top = Rng1.Top
            .Left = Rng1.Left
            .Height = 94.5
            .Width = 144
        End With
        If Cnt Mod ChartsAcross = 0 Then
            Set Rng1 = Rng2.Offset(RowsDown, 0)
            Set Rng2 = Rng1
        Else
            Set Rng1 = Rng1.Offset(0, ColumnsAcross)
        End If
    
    Next

End Sub

Align Charts to Worksheet Grid Post 1

When a series of embedded charts are printed on a page and assuming all of the charts are the same height and width, for a more professional presentation consider aligning the charts horizontally and vertically with an even amount of spacing between. Aligning charts via worksheet cell ranges can help to do so. The code below automates that process and is useful for aligning many embedded charts at one time. There are six inputs:

  • Rng1 - the starting point for the chart at the top left side of the worksheet.
  • ChartsAcross - the number of charts that you want across the worksheet.
  • ColumnsAcross - increments the number of columns between Rng1.
  • RowsDown - increments the number of rows between Rng1.
  • Cht.Height - the height for each chart on the worksheet.
  • Cht.Width - the width for each chart on the worksheet.
Sub AlignCharts()

    Dim Cht As ChartObject
    Dim ChartsAcross As Integer
    Dim ColumnsAcross As Integer
    Dim RowsDown As Integer
    Dim Rng1 As Range
    Dim Rng2 As Range

    Set Rng1 = Range("B2")
    ChartsAcross = 2
    ColumnsAcross = 4
    RowsDown = 10
       
    For Each Cht In ActiveSheet.ChartObjects
        Cht.Height = 94.5
        Cht.Width = 144
    Next Cht

    Set Rng2 = Rng1

    For Each Cht In ActiveSheet.ChartObjects
        Cnt = Cnt + 1
    Next Cht

    For A = 1 To Cnt

        Set Shp = ActiveSheet.Shapes(A)
        Shp.Top = Rng1.Top
        Shp.Left = Rng1.Left

        If Application.WorksheetFunction.Round(A / ChartsAcross, 0) _
        - (A / ChartsAcross) = 0 Then
            Set Rng1 = Rng2.Offset(RowsDown, 0)
            Set Rng2 = Rng1
        Else
            Set Rng1 = Rng1.Offset(0, ColumnsAcross)
        End If

    Next A

End Sub

Given the assumptions above, the code works by first counting the number of charts on the worksheet. The first chart is placed at the top / left of cell B2. An If-Then-Else statement is used to place the following charts to the right of the chart before or to increment to the row range. The statement works by comparing the rounded (integer) value of the chart count divided by the total number of charts against the real number of the chart count divided by the total number of charts. If the divisor has a remainder, the chart is placed to the right of the chart before it. If the divisor does not have a remainder, the range increments to the next row.

The end result given the assumptions above returns the following:

image

Building the Formula Trace Tool Post 1

I spend a good deal of time building and auditing spreadsheets in my position as an analyst in a Finance department. One of the features that has always frustrated me about Excel is the program's ability to audit the spreadsheet. Specifically, the need to double-click on the auditing arrows to move to precedent or dependent cells is, in my opinion, very difficult and inefficient.

Aaron Blood's Explode Add-In converts all of the precedent or dependent cells into cell addresses that appear in a listbox. You can then click on the listbox addresses to move to each cell address in the spreadsheet. The Explode Add-In is a great idea. Unfortunately, the code is protected so I couldn't customize it to my needs.

In this and future posts, I'm going to attempt to create my own formula auditing tool. Like the Explode Add-In, I want to be able to click on formula references to move between precedent and dependent cells. My other qualifications are that the add-in needs to be simple, efficient, and easy to use.

The first challenge to building the Formula Trace Tool add-in is to come up with the code that converts the precedent and dependent cell references to cell addresses. That code is below.

Sub TracePrecedents()

    On Error Resume Next

    Dim Rng As Range
    Dim Adrs As String
    Dim UniqueValues As New Collection
    Dim iArrow As Integer

    Set Origin = ActiveCell

    Origin.ShowPrecedents

    For iArrow = 1 To 1000
        
        Err = 0
        
        Set oPrec = Origin.NavigateArrow(True, iArrow)
        Adrs = oPrec.Parent.Name & " - " & oPrec.Address
        UniqueValues.Add Adrs, CStr(Adrs)
        
        If Err <> 0 Then Exit For

    Next

    Set Rng = ActiveSheet.Range("E3")

    For Each Item In UniqueValues
        Rng.Value = Item
        Set Rng = Rng.Offset(1, 0)
    Next Item

End Sub

To view the output of the procedure, set the active cell to a cell with precedents and run the macro. In the screenshot below, the active cell is C22 and the precedent cells are indicated by the blue auditing references. Each precedent cell is listed in the range E3:E9.

image

Alternatively, get rid of the range references and work in the immediate window. The resulting code is below.

Sub TracePrecedents()

    On Error Resume Next

    Dim Rng As Range
    Dim Adrs As String
    Dim UniqueValues As New Collection
    Dim iArrow As Integer

    Set Origin = ActiveCell

    Origin.ShowPrecedents

    For iArrow = 1 To 1000
        
        Err = 0
        
        Set oPrec = Origin.NavigateArrow(True, iArrow)
        Adrs = oPrec.Parent.Name & " - " & oPrec.Address
        UniqueValues.Add Adrs, CStr(Adrs)
        
        If Err <> 0 Then Exit For

    Next

    For Each Item In UniqueValues
        Debug.Print Item
    Next Item

End Sub

As a sidenote, Microsoft provides a list of error codes as well as selected error handling procedures.

The next step is to try to replace the "Debug.Print Item" statement with some type of listbox load. I'll attempt to address that in the next post of this series.


VLOOKUP Array

I've found that although arrays are not intuitive to most Excel users they can come in very handy at times. For example, a VLOOKUP formula similar to the one below might be a good alternative to beating the limitations of a nested IF statement.

=VLOOKUP(A1,{1,"Jan";2,"Feb";3,"Mar";4,"Apr";5,"May";6,"Jun";7,"Jul";8,"Aug";
9,"Sep";10,"Oct";11,"Nov";12,"Dec"},2,FALSE)