Votre panier est actuellement vide !
Catégorie : Excel VBA Course
Sorting Data on a Protected Sheet with Excel VBA
Data on a protected sheet can be sorted if they are within a range where the Locked property is set to False, and if the AllowSorting parameter of the Protect method is set to True.
The read-only property AllowSorting of the Protection object returns the value of this parameter. For example, the code allows sorting the range A1:A5 on a protected sheet, if it has not been enabled previously.
Sorting on a Protected Sheet
Sub DemoAllowSorting() ActiveSheet.Unprotect Range("A1:A5").Locked = False If ActiveSheet.Protection.AllowSorting Then ActiveSheet.Protect AllowSorting:=True End If End SubSorting List Data by Three Fields with Excel VBA
Let’s consider an example that demonstrates the use of the Sort method. Suppose a worksheet contains a list of data about cars and their owners. Place two CommandButton controls on the worksheet: one will perform ascending sorting by three arbitrary columns, and the other will perform descending sorting.

Change the Caption property values accordingly: for the first button (CommandButton1) set SORT ASCENDING, and for the second button (CommandButton2) set SORT DESCENDING.
Sorting by three fields in ascending and descending order. Standard module
Sub Sort_Up() Range("A1").Select x = InputBox("Enter the column address for sorting by the first field", _ "Enter range") y = InputBox("Enter the column address for sorting by the second field", _ "Enter range") z = InputBox("Enter the column address for sorting by the third field", _ "Enter range") Selection.Sort Key1:=Range(x), Order1:=xlAscending, _ Key2:=Range(y), Order2:=xlAscending, _ Key3:=Range(z), Order3:=xlAscending, Header:=xlYes Range("A1").Select End Sub Sub Sort_Down() Range("A1").Select x = InputBox("Enter the column address for sorting by the first field", _ "Enter range") y = InputBox("Enter the column address for sorting by the second field", _ "Enter range") z = InputBox("Enter the column address for sorting by the third field", _ "Enter range") Selection.Sort Key1:=Range(x), Order1:=xlDescending, _ Key2:=Range(y), Order2:=xlDescending, _ Key3:=Range(z), Order3:=xlDescending, Header:=xlYes Range("A1").Select End SubSorting by three fields in ascending and descending order. Sheet1 module
Private Sub CommandButton1_Click() Sort_Up End Sub Private Sub CommandButton2_Click() Sort_Down End Sub
Using VBA to Sort Data with Excel VBA
Now let’s look at several examples related to sorting data using VBA programs.
To sort data by up to three criteria, the Sort method is applied. This method allows you to sort rows in lists, pivot tables, and databases, as well as columns in worksheets:
expression.Sort(Key1, Order1, Key2, Type, Order2, Key3, Order3, Header, _ OrderCustom, MatchCase, Orientation, SortMethod, DataOption1, _ DataOption2, DataOption3)
- expression — a reference to a cell range or to the range itself that will be sorted.
- Key1 — optional parameter that specifies the reference to the first field to sort.
- Order1 — optional parameter that determines the sort order for the field specified by Key1. Valid values are the following XlSortOrder constants:
- xlAscending (ascending order),
- xlDescending (descending order).
- Key2 — optional parameter that specifies the reference to the second field to sort.
- Type — optional parameter that specifies the elements that should be sorted. Used only with PivotTables.
- Order2 — optional parameter that determines the sort order for the field specified by Key2. Valid values are the XlSortOrder constants.
- Key3 — optional parameter that specifies the reference to the third field to sort.
- Order3 — optional parameter that determines the sort order for the field specified by Key3. Valid values are the XlSortOrder constants.
- Header — optional parameter that specifies whether the first row of the list contains headers. Valid values are the following XlYesNoGuess constants:
- xlYes (the first row of the range contains a header, which is not sorted),
- xlNo (the first row of the range does not contain a header, default value),
- xlGuess (MS Excel decides whether the list has a header).
- OrderCustom — optional parameter that specifies a custom sort order. It is an integer indicating the index number of the list used as a sorting template.
- MatchCase — optional parameter that indicates whether to consider case sensitivity when sorting.
- Orientation — optional parameter that specifies the orientation of the sort. Valid values are the following XlSortOrientation constants:
- xlTopToBottom (sorting is performed top to bottom, i.e., by rows),
- xlLeftToRight (sorting is performed left to right, i.e., by columns).
- SortMethod — optional parameter that specifies the sorting method. Used for languages such as Chinese and Japanese.
- DataOption1 — optional parameter that specifies how text should be sorted in the field defined by Key1. Valid values are the following XlSortDataOption constants:
- xlSortTextAsNumbers (numeric and text data are sorted together),
- xlSortNormal (numeric and text data are sorted separately).
- DataOption2 — optional parameter that specifies how text should be sorted in the field defined by Key2. Valid values are the XlSortDataOption constants.
- DataOption3 — optional parameter that specifies how text should be sorted in the field defined by Key3. Valid values are the XlSortDataOption constants.
Sorting Data WITH Excel VBA
Sorting allows you to arrange data in alphabetical or numerical order, either ascending or descending. Microsoft Excel can sort rows as well as columns of worksheet lists. When sorting text in a table, you can sort a single column or the entire table. In addition, it is possible to sort by multiple words or fields in one table column, as well as for a selected range of the list.
To quickly sort by the desired field, simply place the cell pointer in the required column of the list with data, go to the Data tab, and in the Sort & Filter group click either Sort Smallest to Largest or Sort Largest to Smallest. On the other hand, if you select the Sort button in the Sort & Filter group on the Data tab, a dialog box will open, where you can specify sort keys (columns or rows), the sort order, and some additional parameters.

NOTE
On the Home tab, in the Editing group, there is also a Sort & Filter button, whose commands also allow you to sort a list of data.In MS Excel, the following sort order is used:
- Numbers (from – to +);
- Text and formulas;
- The value FALSE;
- The value TRUE;
- Error values;
- Empty values.
When using sorting, keep in mind:
- The sorting order of data in MS Excel depends on the Windows regional settings.
- If it is necessary to arrange numeric values in alphabetical order, you should either place an apostrophe before the numeric values, format numbers as text, or enter the number as a formula (for example: = »345″).
- When sorting lists containing formulas, remember that relative references in formulas may lead to incorrect results when records are moved. Therefore, it is better to use formulas with absolute references in lists.
- To return to the original list, insert an additional index field before the list, containing an increasing numeric sequence with any step (e.g., 1, 2, 3, …). By selecting a cell in this column and sorting the list in ascending order, you can restore the original order of the list.
- Custom sort order allows you to arrange data in a predefined sequence (for example, days of the week, months, etc.). To do this, use the Custom Lists window , which is called by the Custom List command in the Sort dialog box. Click the order field in the column of this window and choose the Custom List command.

- Dates and times must be entered in the proper format or with the help of date or time functions, since MS Excel uses an internal representation of these values for sorting.
- Sorting by multiple fields is set in the Sort dialog box, starting from the top level. You can change the sort level using the Move Up and Move Down buttons in that dialog box.
- MS Excel can sort not only rows but also columns, as well as a selected range in the list. Furthermore, sorting can be carried out taking into account the case of the entered characters .
What You Need to Know About a List with Excel VBA
Lists in MS Excel are tables, whose rows contain homogeneous information. The rows of a table are called records, and the columns are called fields of records. Each column is assigned a unique field name, which is entered in the first row of the list — the header row.
As a rule, when working with lists you encounter the following ranges:
- Data range — the area where the list data is stored. Related data is written in separate rows, and each column corresponds to its own list field with a unique field name.
- Criteria range — an area on the worksheet where criteria for searching information are specified. In the criteria range, the field names are indicated, and space is allocated for entering selection conditions.
- Extract range — the area into which MS Excel copies the selected data from the list. This range may be located on the same sheet as the list, or on another sheet of the workbook.
Records – Fields – Header Row

Entering data into a list is done, for example, directly into the worksheet cells (i.e., into the empty rows below the header), or by using a data form. To do this, click the list button on the Quick Access Toolbar and choose More Commands. Then, in the Excel Options window, select Quick Access Toolbar on the left, and on the right, in the Choose commands from list, select All Commands. Find the Form command in the list below and add it to the Quick Access Toolbar.
As mentioned earlier, with data placed in a list you can perform: sorting, data filtering, and data analysis.
A Little About Events and Charts with Excel VBA
By default, events are associated with charts that are created on separate chart sheets. Let’s look at some examples of handling events related to charts.
Suppose we need to change the color of the chart area and the chart itself (located on a separate chart sheet) depending on where the mouse click occurs. To handle this event, you can use the code shown in the Chart1 module.
Another example concerns handling the mouse move event on chart sheets. Suppose we want to display additional annotations related to data points in a text box located on the chart sheet .
To implement this example, prepare on Sheet1 the corresponding data table and an annotations table. Then, in the Chart1 module, enter the code.


Linking annotation text to a chart sheet (Chart1 module)
Option Explicit Private Sub Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, _ ByVal X As Long, ByVal Y As Long) Dim RowId As Long Dim rg1 As Long, rg2 As Long Dim MyText As String On Error Resume Next ActiveChart.GetChartElement X, Y, RowId, rg1, rg2 If RowId = xlSeries Then MyText = Sheets("Sheet1").Range("Note").Offset(rg2, rg1) Else MyText = "For information about Nobel Prize winners, " & _ "select a column in the chart." End If ActiveChart.Shapes(1).TextFrame.Characters.Text = MyText End SubLinking Events to Embedded Charts
If a chart is embedded in a worksheet, you cannot directly link events to it. In this case, you need to perform several additional steps before you can bind the required events to charts located on worksheets.
As a small example, do the following:
- Open the VBA editor and create a class module named MyEventClassModule (Insert | Class Module, then set the Name property to MyEventClassModule).
- Declare in the class module a variable of type Chart with the keyword WithEvents. After that, in the code editor, the object MyEventClassModule will appear in the object list, and all events associated with charts will appear in the event list.
Linking events to embedded charts. Class module MyEventClassModule (version 1)
Public WithEvents MyChartClass As Chart
- In the code editor, enter the code for handling the events needed for your project’s business logic. For example we link the mouse button click to a message: “Think about your next steps!”
Linking events to embedded charts. Class module MyEventClassModule (version 2)
Private Sub MyChartClass_MouseDown(ByVal Button As Long, _ ByVal Shift As Long, ByVal x As Long, ByVal y As Long) MsgBox "Think about your next steps!" End Sub
- Link the event to the embedded chart. For example, this can be done at the workbook open stage by adding to the ThisWorkbook module the code. This associates the first embedded chart on the first worksheet with the MyChartClass object. Now, when you click the mouse on this chart, the message “Think about your next steps!” will appear.
Linking events to embedded charts. ThisWorkbook module
Dim MyClassModule As New MyEventClassModule Sub ChartInit() Set MyClassModule.MyChartClass = Worksheets(1).ChartObjects(1).Chart End Sub Private Sub Workbook_Open() ChartInit End Sub
Changing Chart Type via Context Menu
As another example of using chart events for embedded charts, let’s consider a project where, when you right-click the chart, a context menu appears with the following commands: Column, Line, Doughnut, Area, Bar, and Cone. Selecting one of these changes the chart to the corresponding type.

First, the event to handle is the right-click on an embedded chart. Therefore, you need to create a class (in this case ChartEventClass) where the code to handle this event is implemented. When the workbook is opened, the instance of ChartEventClass is linked to the specific chart, the context menu is created, and the commands of this menu are assigned macros that perform the chart type change.
Protecting a Chart Embedded in a Worksheet with Excel VBA
If you want to protect a chart built on a worksheet, as well as the worksheet data outside a certain range, use the Protect method of the Worksheet object with the parameter UserInterfaceOnly set to True. This will protect the worksheet and allow data entry only in the specified cells. For example, to protect all worksheet objects except the range B4:G13, add the code from Listing 6.8 to the ThisWorkbook module.
To allow data entry on the worksheet, go to the Review tab on the ribbon and, in the Changes group, click Unprotect Sheet. Typically, you will be prompted to enter the password (in our case, « pass »).

Setting protection on an embedded chart. ThisWorkbook module
Private Sub Workbook_Open() SetPtotection End Sub Private Sub SetPtotection() On Error Resume Next Worksheets("Vedomost").Range("B4:G13").Locked = False Worksheets("Vedomost").Protect Password:="pass", UserInterfaceOnly:=True End SubNote
If you add protection to a worksheet that contains controls, attempting to use the controls may cause a project error. Remove the sheet protection and perform the usual actions.Protecting a Chart on a Separate Chart Sheet
To protect a chart located on a separate chart sheet (a Chart object), use the Protect method:
Protect(Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly)
- Password — sets the protection password.
- DrawingObjects — protects drawing objects.
- Contents — protects the entire chart.
- Scenarios — protects scenarios.
- UserInterfaceOnly — protects the user interface but not macros. If this parameter is omitted, the protection applies to both the interface and macros.
You can remove protection using Unprotect:
Unprotect(Password)
Listing shows how to protect a chart located on a separate sheet, and also how to lock all cells on worksheet Sheet1 for the user, except the range B4:G13.
Setting protection on a chart. ThisWorkbook module
Private Sub Workbook_Open() SetPtotection End Sub Private Sub SetPtotection() On Error Resume Next Charts(1).Protect Password:="d1", UserInterfaceOnly:=True Worksheets("Sheet1").Range("B4:G13").Locked = False Worksheets("Sheet1").Protect Password:="1" End SubBuilding Surface Charts and Controlling Orientation with Excel VBA
Let us now look at an example of creating a surface chart, which naturally has a three-dimensional orientation. As the data source, we will once again use the report of the computer club network’s performance. The surface will be created automatically from the table when the workbook is opened:
- the x-axis will represent the names of the clubs,
- the y-axis will represent the months,
- the z-axis will represent the clubs’ revenues.
Clearly, the clarity of a surface chart greatly depends on the side and angle from which the user views it. Therefore, in addition to programming the chart creation process, we will place two control elements (lists) on the worksheet.
- The first list is intended for changing the elevation angle from which the surface is viewed. Set its Name property to Elev.
- The second list is intended for rotating the surface around the z-axis. Set its Name property to Rotat.
When the worksheet is activated, the lists are populated with permissible angles. In the ThisWorkbook standard module and the Vedomost worksheet module, enter the code for the corresponding procedures.

As another example, let us consider a surface chart where the rotation takes place in three dimensions.

To implement this example, perform the following steps:
- Prepare the data range for the chart. Enter values into cells A1:A16 and B1:L1 for the x-axis (interval: –1 to 6.5, step: 0.5) and y-axis (interval: –1 to 1.2, step: 0.2).
In cell B2, enter the formula for z = cos(x)cos(y)sin(xy):
=COS($A2)*COS(B$1)*SIN($A2*B$1)
Copy this formula across the range B2:L16.
- Select the range A1:L16 and build a surface chart using Excel’s built-in tools: go to the Insert tab on the ribbon, in the Charts group click Other Charts, and choose the type Surface.
- Format the resulting surface using the features of the contextual Chart Tools tabs.
- Place three CommandButton controls on the worksheet and set their Caption properties as follows:
- ROTATION (for CommandButton1),
- TURN (for CommandButton2),
- PERSPECTIVE (for CommandButton3).
- Enter in a standard module and in the worksheet module Surface_Rotation the code for the procedures that support surface rotation in three dimensions.
Creating a Project with a Trendline with Excel VBA
Quite often, it is desirable to see certain trends in the data presented on a chart. In such cases, you can add a trendline, which makes it possible to forecast values.
If you want to add a trendline using Microsoft Excel’s built-in tools, activate the chart, go to the Layout contextual tab on the ribbon, and in the Analysis group click the Trendline drop-down list, then choose the desired type of trendline. Remember that a trendline is always constructed for the selected data series; therefore, if the chart contains multiple series, you need to specify for which series the trendline should be built. Alternatively, you can select the desired series directly on the chart and, from the context menu, choose Add Trendline.
From the VBA perspective, all trendlines corresponding to a given data series form the Trendlines collection, whose elements are Trendline objects. The Trendlines collection has only two methods:
- Add — adds a new element to the collection,
- Item — returns a specific element from the collection.
The Trendline object has the same properties as the parameters of the Add method (see Microsoft VBA Help).
Description of the Add method of the Trendlines collection
Add(Type, Order, Period, Forward, Backward, Intercept, DisplayEquation, DisplayRSquared, Name)
- Type — sets the type of trendline. Valid values:
- xlLinear (linear),
- xlLogarithmic (logarithmic),
- xlExponential (exponential),
- xlPolynomial (polynomial),
- xlMovingAvg (moving average),
- xlPower (power).
- Order — sets the order of the polynomial trendline (valid integers 2 to 6; used only if Type = xlPolynomial).
- Period — trend period (valid integers 1 to the number of data points; used only if Type = xlMovingAvg).
- Forward — number of points forward (future) to forecast.
- Backward — number of points backward (past) to forecast.
- Intercept — intercept on the y-axis.
- DisplayEquation — Boolean, whether to display the trendline equation on the chart.
- DisplayRSquared — Boolean, whether to display the R² (coefficient of determination) value.
- Name — string specifying the name of the trendline.
Example: Trendline in the Computer Club Project
In our last project, we will add a group of CheckBox controls that allow the user to manage the display of the trendline on the chart (Fig. 6.10; see also file 7-Building a Trendline.xlsm on the CD).
On the Vedomost worksheet, add three checkboxes and, in the Properties window, set their properties as shown in Table.

Table. Values of properties set in the Properties window
Control Property Value CheckBox Name Trend Caption Trendline CheckBox Name Equation Caption Equation CheckBox Name Coef Caption R-squared value Open the previous project related to computer clubs and make the following additions. In the Vedomost worksheet module, add the code for the three Click event procedures of the checkboxes:
- The Trendline checkbox builds or removes the trendline. If the trendline is removed, the Equation and R-squared checkboxes are disabled.
- The Equation checkbox controls whether the equation of the trendline is displayed.
- The R-squared checkbox controls whether the coefficient of determination is displayed.
Trendline. Vedomost worksheet module
Private Sub Trend_Click() Dim c As Chart On Error Resume Next If DType.Text = xlPie Or DType.Text = xlDoughnut Then Exit Sub ActiveSheet.ChartObjects(1).Activate Set c = ActiveChart If Trend.Value Then Equation.Enabled = True Coef.Enabled = True c.SeriesCollection(1).Trendlines.Add _ Type:=xlLinear, Forward:=0, Backward:=0, _ DisplayEquation:=False, DisplayRSquared:=False If Trend.Value Then c.SeriesCollection(1).Trendlines(1).DisplayEquation = False End If If Coef.Value Then c.SeriesCollection(1).Trendlines(1).DisplayRSquared = True End If Else c.SeriesCollection(1).Trendlines(1).Delete Equation.Enabled = False Coef.Enabled = False End If End Sub Private Sub Equation_Click() On Error Resume Next If DType.Text = xlPie Or DType.Text = xlDoughnut Then Exit Sub If Trend.Value Then Dim c As Chart ActiveSheet.ChartObjects(1).Activate Set c = ActiveChart If Equation.Value Then c.SeriesCollection(1).Trendlines(1).DisplayEquation = True Else c.SeriesCollection(1).Trendlines(1).DisplayEquation = False End If End If End Sub Private Sub Coef_Click() On Error Resume Next If DType.Text = xlPie Or DType.Text = xlDoughnut Then Exit Sub If Trend.Value Then Dim c As Chart ActiveSheet.ChartObjects(1).Activate Set c = ActiveChart If Coef.Value Then c.SeriesCollection(1).Trendlines(1).DisplayRSquared = True Else c.SeriesCollection(1).Trendlines(1).DisplayRSquared = False End If End If End Sub
In the ThisWorkbook module, add the following procedure to set the initial states of the checkboxes . Naturally, the call to InitTrend must also be added to the Workbook_Open procedure in the same module.
Trendline. ThisWorkbook module
Private Sub InitTrend() With Worksheets("Vedomost") .Trend.Value = False .Equation.Value = False .Coef.Value = False End With End SubSequentially Displaying Data Series in a Chart with Excel VBA
By default, in Microsoft Excel, charts do not display data contained in hidden rows or columns. In this example, we will illustrate a simple way to hide and display data series in a chart. As control elements for visualizing or hiding a data series—both in the worksheet and in the chart we will use checkboxes.

To implement this example, follow these steps:
- Prepare a table on the worksheet showing product sales by months.
- Build a chart for the prepared data: go to the Insert tab on the ribbon, and in the Charts group, choose from the Line list the chart type Line with Markers.
- Format the resulting chart.
- Add five CheckBox controls on the worksheet in sequence and set the Caption property for each of them respectively to: Ruler, Pencil Case, Pen, Pencil, Eraser.
- In the Sheet1 worksheet module, add event-handling procedures for the Click events of the CheckBox controls.