Votre panier est actuellement vide !
Catégorie : Excel VBA Course
Consolidation Using 3D Formulas on a Worksheet with Excel VBA
As an example of consolidation using 3D formulas, let’s consider a business case of building a consolidated table of expenses for the company Alliance LLC for the reporting period from January to March. These expenses are collected in tables located on the worksheets January, February, and March. The company’s expenses are detailed quarterly.
So:
- Create a worksheet called Totals, where you will place the template of the report table.
- Enter in cell B3 the formula that calculates the total expenses for telephone in the first quarter from January through March:
=SUM(January:March!B3)
or the equivalent formula:
=SUM(January!B3,February!B3,March!B3)

- Place the mouse pointer on the fill handle and drag it down and to the right over the range B3:E8. This will allow you to calculate the total expenses for each category of expenses from June through August.
Consolidation Using 3D Formulas in Code
The procedure for creating a consolidated table based on 3D formulas, described in the previous section, can be automated with the following code.
The code includes a check for the existence of a worksheet named Totals. If such a sheet does not exist, it is created; if it already exists, a message is displayed and the process of building the consolidated table is interrupted.
Consolidation Using 3D Formulas
Sub DemoConsolidate3D() Dim rgn As Range Dim ws As Worksheet Dim str As String Dim nm As String nm = "Totals" For Each ws In Worksheets str = str & ws.Name & "!B3" & ";" If ws.Name = nm Then MsgBox "The Totals sheet already exists" Exit Sub End If Next str = Left(str, Len(str) - 1) Worksheets.Add After:=Worksheets(Worksheets.Count) ActiveSheet.Name = nm Worksheets("January").Range("A1:E8").Copy Worksheets(nm).Range("A1:E8") Range("B3:E8").Clear Range("B3").FormulaLocal = "=SUM(" & str & ")" Range("B3").AutoFill Destination:=Range("B3:B8"), Type:=xlFillDefault Range("B3:B8").AutoFill Destination:=Range("B3:E8"), Type:=xlFillDefault End SubNested Subtotals with Excel VBA
Nested subtotals involve creating several levels of nesting for a single data list.
Nested subtotals are calculated as follows:
- Prepare the data list and place the cell pointer within it. Decide which totals you need — by levels of nesting.
- Sort by the required fields (use the Sort dialog box, which opens when executing the Sort command located in the Sort & Filter group on the Data tab of the ribbon).
- Calculate the totals using the Subtotal dialog box (which opens when executing the Subtotal command located in the Outline group on the Data tab of the ribbon).
When creating nested subtotals, you should clearly understand the levels of totals and create them in the order of increasing detail: first — by the primary sort field, then, disabling the Replace current subtotals option (in the Subtotal dialog box) — by the second field, and so on.
Now let’s look at an example of nested subtotals, using the same sales list. Suppose we need to obtain the total number of products sold by a specific seller, taking into account the particular sale date.
- Select the list (or place the cell pointer in the list) and sort it (execute the Sort command located in the Sort & Filter group on the Data tab of the ribbon) by the fields Seller and Sale Date. To add each subsequent field in the Sort dialog box, click the Add Level button.

- Use the Subtotal command located in the Outline group on the Data tab of the ribbon.
- In the Subtotal dialog box that opens, set the parameters according to obtain the upper (first) level of totals — the total number of products sold by a specific seller.
- To obtain the second level of totals in the same list with the calculated subtotals, place the cell pointer back into the list and then use the Subtotal command again.
- In the Subtotal dialog box that opens, set the parameters according.

- The resulting subtotals are shown in Fig.

NOTE
When subtotals are added to a list, the list layout changes so that its structure becomes visible. By pressing the outline buttons , and , you can create a summary report by hiding details and showing only totals.The Subtotal Method
The Subtotal method of the Range object adds subtotals to a data list based on changes in specified data fields. Subtotals allow summarizing data. The Subtotal method automatically inserts rows containing formulas that calculate the subtotals. It is necessary to sort the data correctly before activating this method; otherwise, the method may produce incorrect results. The Subtotal method is equivalent to executing the Subtotal command located in the Outline group on the Data tab of the ribbon.
expression.Subtotal(GroupBy, Function, TotalList, Replace, PageBreaks, SummaryBelowData)
- expression — a reference to the cell or the entire range for which the subtotals are calculated.
- GroupBy — required parameter, specifies the field number by which the subtotals are calculated.
- Function — required parameter, specifies the function used for calculating the subtotals. The acceptable values are the following XlConsolidationFunction constants:
- xlAverage (arithmetic mean),
- xlCount (number of values),
- xlCountNums (number of numbers),
- xlMax (maximum),
- xlMin (minimum),
- xlProduct (product),
- xlStDev (unbiased deviation),
- xlStDevP (biased deviation),
- xlSum (sum),
- xlVar (unbiased variance),
- xlVarP (biased variance).
- TotalList — required parameter, specifies an array of integers with the numbers of the fields for which subtotals are calculated.
- Replace — optional Boolean parameter. If True, existing subtotals will be replaced.
- PageBreaks — optional Boolean parameter. If True, a page break will be inserted after each group.
- SummaryBelowData — optional parameter that sets the location of the subtotals. Acceptable values are the following XlSummaryRow constants:
- xlSummaryAbove (subtotals will be displayed above the data),
- xlSummaryBelow (subtotals will be displayed below the data).
Removing Subtotals
The RemoveSubtotal method of the Range object removes subtotals from a worksheet.
For example, the following instruction removes subtotals associated with the range A1:I40:Range("A1:I40").RemoveSubtotalSimple Subtotals with Excel VBA
Simple subtotals are calculated as follows (subtotal method):
- Prepare the data list and place the cell pointer within it. Decide which totals you need.
- Sort by the required field (for example, use the Sort dialog box, which opens when executing the Sort command located in the Sort & Filter group on the Data tab of the ribbon).
- Calculate the totals using the Subtotal dialog box (it opens when executing the Subtotal command located in the Outline group on the Data tab of the ribbon).
TIP
To remove subtotals, place the pointer in the list with totals and use the Remove All button in the Subtotal dialog box.Now, let’s look at an example of calculating simple subtotals. Suppose we have a data list with the following fields:

No., Seller, Product, Batch Number, Price, Quantity, Total, Sale Date, Customer. The task is to determine the number of products sold by a specific seller.
To calculate simple subtotals, perform the following steps:
- Select the list (or simply place the cell pointer in the list) and sort it (execute the Sort command located in the Sort & Filter group on the Data tab of the ribbon) by the Seller field

- Use the Subtotal command located in the Outline group on the Data tab of the ribbon.
- In the Subtotal dialog box that opens, set the parameters according

and click OK.
- The resulting subtotals are shown :

A Few Words About the AdvancedFilter Method with Excel VBA
The AdvancedFilter method for the Range object allows you to programmatically perform advanced filtering of a list according to criteria specified in the parameters:
expression.AdvancedFilter(Action, CriteriaRange, CopyToRange, Unique)
- expression — a reference to a cell in the range or to the range itself that will be filtered.
- Action — a constant that specifies whether to keep the filtered data on the worksheet (xlFilterInPlace) or copy it elsewhere (xlFilterCopy).
- CriteriaRange — optional parameter specifying the criteria range; if omitted, no criteria are applied.
- CopyToRange — optional parameter specifying the range where the filtered data will be copied if xlFilterCopy is chosen.
- Unique — parameter specifying whether only unique values should remain in the filtered range. Accepts values True or False; the default is False.
Demonstration Example
Suppose the worksheet contains weather data. The task is to determine cities:
- where air pressure is greater than the maximum value for the city of Grodno, or
- where precipitation is either rain or snow, and its amount exceeds the average for all types of precipitation by no more than 23%.
Steps:
- Open the list to be filtered (range A1:I49, header row A1:I1, worksheet Precipitation).
- Prepare the calculated criterion for the Advanced Filter in the range L1:L2 (Fig. 7.15).
- Cell L1 contains the word Condition.
- Cell L2 contains the formula:
=OR(AND(C2<>"Grodno",G2>MAX($G$26:$G$33)), AND(OR(D2="rain",D2="snow"), OR(AND((E2-AVERAGEIF($D$2:$D$49,"rain",$E$2:$E$49))/AVERAGEIF($D$2:$D$49,"rain",$E$2:$E$49)*100>0, (E2-AVERAGEIF($D$2:$D$49,"rain",$E$2:$E$49))/AVERAGEIF($D$2:$D$49,"rain",$E$2:$E$49)*100<23), AND((E2-AVERAGEIF($D$2:$D$49,"snow",$E$2:$E$49))/AVERAGEIF($D$2:$D$49,"snow",$E$2:$E$49)*100>0, (E2-AVERAGEIF($D$2:$D$49,"snow",$E$2:$E$49))/AVERAGEIF($D$2:$D$49,"snow",$E$2:$E$49)*100<23))))

- Place two CommandButton controls on the worksheet. One button will perform data filtering, the other will remove the filter.
- Set the Caption property for the first button (CommandButton1) to Filter, and for the second (CommandButton2) to Remove Filter.
- Enter the program code shown in Listing 1 in a standard module, and the code in Listing 2 in the Sheet1 module.
Listing 1. Advanced Filtering — Standard Module
Sub AdFilt() Range("A1:I49").AdvancedFilter Action:=xlFilterInPlace, _ CriteriaRange:=Range("L1:L2"), Unique:=True End Sub Sub Del() Worksheets("Precipitation").ShowAllData End SubListing 2. Advanced Filtering — Sheet1 Module
Private Sub CommandButton1_Click() AdFilt End Sub Private Sub CommandButton2_Click() Del End Sub
- Now, to obtain the filtered data according to the criteria, simply click the Filter button located on the Precipitation worksheet. To remove the filter, click the Remove Filter button.
How to Use the Advanced Filter with Excel VBA
The Advanced Filter provides the user with more options for specifying selection criteria, taking into account AND, OR, and calculated criteria. Searching with the Advanced Filter is carried out according to the following guidelines:
- Prepare the criteria range for the Advanced Filter:
- The top row contains the field headers on which the selection will be based (these must exactly match the field headers of the list).
- The search criteria are entered into the empty rows below the prepared header row. Keep in mind:
- To apply an AND condition, place the criteria side by side in the same row.
- To apply an OR condition, place the criteria on different rows.
- To use a calculated criterion, include formulas (custom or Excel functions) whose arguments are fields of the list.
- The calculated criterion is placed under a custom header (for example, Condition), which must not match any existing field name of the list.
- Relative references are used for list fields, pointing to the top record in the list’s data range.
- References to cells outside the list must be absolute.
- The result of evaluating the criterion must be a logical value (TRUE or FALSE). The Advanced Filter selects records where the result is TRUE.
- In the case of complex conditions, the search is carried out using composite criteria with AND and OR. The criterion should be constructed with logical functions AND(), OR(), NOT().
- Place the cell pointer in the list (select the entire required list or a part of its range).
- Go to the Data tab on the ribbon, and in the Sort & Filter group, click the Advanced button. In the Advanced Filter dialog box:
- Specify the location where the filtered results should be placed.
- In the List range field, mark the entire list to be filtered (if the pointer was placed in the list, this range is selected by default).
- In the Criteria range field, specify the prepared criteria range (you can select it directly on the worksheet with the mouse).
- If the filtered records need to be copied elsewhere, specify the Copy to range.
- To filter out only unique records (without duplicates), select the checkbox Unique records only.

The results of the Advanced Filter are displayed on the same worksheet or copied to another location.
Examples
Example 1. Determine if the list contains yellow or black cars, manufactured after 2003, priced between 2,500 and 15,000 USD, or beige Mercedes cars with mileage greater than 20,000 km but less than 100,000 km.
- Open the list to be filtered (range A1:J58, header row A1:J1, worksheet Cars_List-1).
- Prepare the criteria range for the Advanced Filter.

- Go to the Data tab, in the Sort & Filter group, click Advanced.
- In the Advanced Filter dialog box, specify the required ranges and filter parameters. Click OK.

Example 2. Determine if the list contains cars manufactured after 2000 with mileage greater than 10,000 km but less than 100,000 km, or black Mercedes cars priced between 20,000 and 30,000 USD.
- Open the list to be filtered (range A1:J133, header row A1:J1, worksheet Cars_List-2).
- Prepare the calculated criterion for the Advanced Filter in the range M3:M4.
- Cell M3: enter the word Condition.
- Cell M4: enter the formula:
=OR(AND(G2>10000,G2<100000,D2>2000),AND(C2="Mercedes",F2="black",H2>20000,H2<30000))
- On the Data tab, in the Sort & Filter group, click Advanced.
- In the Advanced Filter dialog box, specify the required ranges and filter parameters. Click OK.
- The filtered data will be displayed on the worksheet.

Example 3. Determine white or red cars whose price is lower than the average price of all cars, and whose mileage is greater than or equal to the average mileage.
- Open the list to be filtered (range A1:J133, header row A1:J1, worksheet Cars_List-3).
- Prepare the calculated criterion for the Advanced Filter in the range L1:L2:
- Cell L1: enter the word Condition.
- Cell L2: enter the formula:
=AND(OR(F2="white",F2="red"),H2<AVERAGE($H$2:$H$133),G2>=AVERAGE($G$2:$G$133))
- On the Data tab, in the Sort & Filter group, click Advanced.

- Prepare the criteria range for the Advanced Filter:
Example of an Application for Filtering Data with Excel VBA
Let’s consider the creation of an application that filters data for a specified column in a data list.
First, create a workbook and rename Sheet1 to List. Delete the remaining worksheets of the workbook. Place the prepared table of data about cars and their owners on the List sheet.
When you right-click the table header, a context menu should appear with a single command: Filter. Selecting this command should call a dialog box asking for the address of the header cell of the data list. After specifying the cell address, a form should appear with a list box containing the values from that column and a check box labeled Filter.
- If the check box is selected, the data on the worksheet will be filtered by the value chosen in the list.
- If the check box is cleared, the filter will be removed.

Now, create a form and place on it a ListBox and a CheckBox. Using the Properties window, set the Name property of the form to frmFilter.
Enter the corresponding code in the form module, in the ThisWorkbook module, and in a standard module.
In the Form Module
There are three procedures:
- Form Initialize event procedure — sets the Caption properties of the check box and form, and fills the list. The list is filled with values from the column of the table whose first cell address is entered by the user. Duplicate values are skipped during filling.
- ListBox Change event procedure — when an item is selected in the list, if the Filter check box is selected, the table is filtered. If AutoFilter arrows have not yet been displayed in the table, this procedure first initializes AutoFilter and then performs filtering.
- CheckBox Change event procedure — depending on the state of the check box, either performs filtering (by calling the list box Change event procedure) or removes AutoFilter.
In the ThisWorkbook Module
There are three procedures:
- Workbook Open event procedure — creates a context menu with a single item Filter, linked to the procedure DoFilter.
- Workbook SheetBeforeRightClick event procedure — displays the context menu when the user right-clicks the first row of the List sheet.
- Workbook BeforeClose event procedure — deletes the context menu from the workbook when the workbook is closed.
In the Standard Module
There is a single procedure DoFilter, which displays the Field_Name window.
How to Program AutoFiltering with Excel VBA
The AutoFilter method of the Range object allows you to programmatically apply AutoFilter to a list according to criteria specified in its parameters:
expression.AutoFilter(Field, Criteria1, Operator, Criteria2, VisibleDropDown)
- expression — a reference to a cell in the range or to the range itself that will be filtered.
- Field — optional parameter specifying the number of the field (column) in which data will be filtered. Numbering starts from the leftmost field, where the first field has the number 1.
- Criteria1 and Criteria2 — optional parameters specifying up to two criteria for filtering the field. You can use a string constant, for example « 101 », and relational operators >, <, >=, <=, =, <>. Use = to filter empty fields and <> to filter non-empty fields. If the parameter is omitted, the criterion is All. If the parameter Operator equals xlTop10Items, then Criteria1 defines the number of displayed items (for example, « 30 »).
- Operator — optional parameter. Valid values are the following XlAutoFilterOperator constants:
- xlAnd (logical AND of the first and second filter criteria),
- xlOr (logical OR of the first and second criteria),
- xlTop10Items (displays the top 10 items of the field),
- xlBottom10Items (displays the bottom 10 items of the field),
- xlTop10Percent (displays the top 10% of items),
- xlBottom10Percent (displays the bottom 10% of items).
- VisibleDropDown — optional parameter (Boolean). Determines whether drop-down arrows are shown. Default is True.
When writing VBA programs that use AutoFilter, the following methods and properties are also helpful:
- The AutoFilter method of the Range object, used without parameters, displays or hides the AutoFilter arrows.
- The ShowAllData method of the Worksheet object displays all data in the list—both filtered and unfiltered. Example:
- Worksheets(« Orders »).ShowAllData
- The AutoFilterMode (read-only) property of the Worksheet object returns True if AutoFilter arrows are present on the worksheet.
- The FilterMode (read-only) property of the Worksheet object returns True if filtered data with hidden rows exists on the worksheet.
The AutoFilter object encapsulates the data about the AutoFilter used on a worksheet. This object is returned by the AutoFilter property of the Worksheet object.
Table. Main properties of the AutoFilter object
Property Description Filters Returns a collection of Filter objects, i.e., all filters that form the given AutoFilter. The properties of the Filter object are given in Table 7.2. For the Filters collection, the main properties are Count and Item, which return the number of items and a specific item in the collection. Range Returns the range to which the filter is applied. Table. Properties of the Filter object
Property Description On Returns True if the filter is applied. Criteria1 Returns the first filter criterion. Criteria2 Returns the second filter criterion. Operator Returns the filter operator. Valid values are the XlAutoFilterOperator constants. Note also that the EnableAutoFilter property of the worksheet allows you to control access to AutoFilter drop-down lists on a protected sheet. If its value is True, the AutoFilter drop-down lists are available to the user even when the worksheet is protected. In this case, protection must be enabled for the user interface only:
ActiveSheet.EnableAutoFilter = True ActiveSheet.Protect Contents:=True, UserInterfaceOnly:=True
As an example, consider a procedure using the AutoFilter object. In the standard module, place the procedure code that first determines whether an AutoFilter exists on the worksheet, and if so, retrieves the total number of filters and the filter criteria for the applied custom AutoFilters. In the Sheet1 module, place the code that handles the button click.
How to Find Data Using AutoFilter with Excel VBA
If you use AutoFilter to search for data in a list, arrows appear to the right of the column headers in the filtered list. For filtered data, the row numbers are highlighted in blue, and the AutoFilter arrow changes into a funnel (filter) symbol next to the fields by which the data has been filtered.
In the AutoFilter drop-down list you can:
- Sort data by selecting Sort Smallest to Largest or Sort Largest to Smallest.
- Sort data by color, using the Sort by Color command; in the drop-down list next to this command, you can define a custom sort order.
- Remove a filter from a field, using the command Clear Filter From « Field_Name ».
- Apply a filter by color, using the Filter by Color command.
- Specify a numeric range for filtering data, using Number Filters. In the drop-down list next to this command, you can select Custom Filter, which opens the Custom AutoFilter dialog box, where a simple filter criterion with up to two conditions can be set.
- Search for data using the Search box by entering a criterion for exact match or approximate match using a pattern.
- Select a field value for an exact match search.

Searching with AutoFilter is done in the following order:
- Place the cell pointer within the data list.
- Go to the Home tab of the ribbon, in the Editing group click the Sort & Filter button and select Filter, or use the Filter command located in the Sort & Filter group on the Data tab of the ribbon. AutoFilter arrows will appear next to each field in the header row of the list.
- Go to the required field.
- Choose the desired search criterion or use the Custom AutoFilter. Note that the Custom AutoFilter dialog box allows you to quickly set more complex conditions than a simple comparison. In the top-left drop-down list, select a comparison operator (in this case, greater than or equal to), and in the right-hand field, enter or select a value (here: 9000). Then, if necessary, choose either the AND or OR operator, set the second comparison operator and value. In this example, the AND option is chosen, the operator less than, and the value 20000. Finally, click OK to obtain the result of the custom filter.
- To include another field in the criterion, return to step 3.

Sorting All Columns of a List with Excel VBA
In Microsoft Office Excel 2010, by using the Sort dialog box, you can specify in sequence how and by which columns the data should be sorted. However, if you need to sort the entire list in ascending or descending order, taking into account all the columns that belong to the list, follow the example below.
- First, place a list with data on the worksheet. For example, let’s again use our list of car owners.
- Add two CommandButton controls. The first button will perform ascending sorting for all columns of the list, and the second button will perform descending sorting.

- Change the Caption property values of the buttons respectively to:
- SORT ASCENDING FOR ALL COLUMNS
- SORT DESCENDING FOR ALL COLUMNS
- Add the program code that performs the sorting to a standard module, and the program code that handles the button clicks to the Sheet1 module.
Sorting Data in a Selected Range with Excel VBA
Now let’s look at an example of sorting list data, but only for a pre-selected range of the list. As source data, we again use a table of cars and their owners.
On the worksheet, add a CommandButton control, and change its Caption property value to:
SORT ALL COLUMNS FOR THE SELECTED RANGE OF THE LIST.Sorting list data by a selected range. Standard module
Sub SortColumnUp() Dim k As Long For k = Selection.Columns.Count To 1 Step -1 Selection.Sort Key1:=Selection.Cells(2, k), Order1:=xlAscending, _ Header:=xlGuess, Orientation:=xlTopToBottom Next k End Sub
Sorting list data by a selected range. Sheet1 module
Private Sub CommandButton1_Click() SortColumnUp End Sub