Visual Basic for Applications (VBA) has its origins in Visual Basic, a programming language developed by Microsoft. It is important to understand that VBA is not a standalone program, meaning that you cannot compile code and run it as a separate program outside the MS Office environment.
Its main reason for existence is the customization of the MS Office host applications in which it runs: Word, Excel, Access, PowerPoint, Visio, and Publisher. Companies such as Corel also make use of VBA to allow customization of their applications.
Customization involves the recording and creating of macros to automate repetitive tasks. It is also used to generate custom forms, including event-driven buttons and fields.
Like any language, you need to understand the structure of VBA, which is a programming language. It starts with vocabulary. From there, you learn what effects certain words, also known as commands, will have. The more you use the language, the better you understand it. So, if you want to use VBA to its full potential, this chapter will empower you, in every sense of the word, in doing the following:
By the end of this chapter, you will be able to use VBA language elements.
This cookbook was written and designed to be used with MS Office 2019 and MS Office 365, installed on either Windows 8, 8.1, or 10. If your hardware and software meet these requirements, you have everything you need.
Demonstration files can be downloaded from https://github.com/PacktPublishing/VBA-Automation-for-Excel-2019-Cookbook.
Please visit the following link to check out the CiA videos: https://bit.ly/3jQRvVk.
In this recipe, we will be working with comments. Before we start, you need to understand three important principles about comments:
Comments, or notes, serve as a reminder to yourself. You sometimes create complex sequences for a client, save the file, and move on. When you later see that macro again and need to make adjustments, you will be shocked to realize how little you remember of the thinking process you went through to create that macro.
Comments also serve as an explanation for someone else that might have to amend your coding. Instead of trying to waste time on trying to figure out your thought process, comments make a world of difference for that person.
Open Excel and make sure that Book1 is active. Save the file as Comments.xlsm.
Let's start with the steps:
a. Call the macro Comments.
b. Add a shortcut key: Ctrl + Shift + Q.
c. In the Comments section, type Demonstrate the use of comments.
d. Format cells A1:E1 as bold, 12pt, and center.
e. Format cells A2:E7 as Accounting.
f. For cells A7:E7, add a single line to the top and a double line at the bottom.
g. Select cell F1 before stopping the recording.
The first six comments were automatically added during the recording of the macro.
When recording a macro, the VBA Editor will insert some comments automatically. Extra comments can be added manually. Start a comment by first inserting the single apostrophe symbol ('). The VBA Editor will not interpret text following the apostrophe as code.
Comments can be inserted anywhere you want in either of the following ways:
There is an exception to this rule, however. You cannot insert a comment in the middle of a line of code, because the apostrophe will cancel out all the code following it.
Before confusing you with the definition of what a variable is, it helps a lot to first understand where and how variables can be used. Let's use the following example.
Imagine you are capturing data on a standard Excel spreadsheet. The fields expect users to enter their name, the department they work in, and age, all on Sheet1 of a workbook. The captured data must then be stored on a separate sheet, most likely Sheet2 of the same workbook.
The longest, most difficult way of doing that would be to copy the data from Sheet1 and paste it manually into Sheet2. It is quite clear that automation would save a lot of time.
The question is how to achieve this automation. Without some way of automatically copying and then storing that data somehow, somewhere, and then pasting it in the new position, you will never get around to doing any other work than just that.
Automation would be something like the following. You enter your details on Sheet1, and then run a macro to copy the details in order to automatically populate the table on Sheet2. Enter data, copy and store, then paste—all in one action!
The problem here is how to copy and store the entries from Sheet1. That is where variables come in. A variable is simply a line of VBA coding with the purpose of storing information on a temporary basis. This stored information can be accessed repeatedly while the Excel file is open, but is not stored when the application is closed.
There is a lot more to be said about variables, such as naming conventions, data types, and scope, but more about that later.
In this recipe, we will be declaring and using variables.
Open Excel and make sure that Book1 is active.
The steps to create or declare a variable are as follows:
Sub Form_Data()
End Sub
Sub Form_Data()
Dim Name As String
Dim Dept As String
Dim Age As Integer
End Sub
We will discuss data types in the next recipe.
Sub Form_Data()
Dim Name As String
Dim Dept As String
Dim Age As Integer
Name = Sheet1.Range("B1").Value
Dept = Sheet1.Range("B2").Value
Age = Sheet1.Range("B3").Value
End Sub
Sub Form_Data()
Dim Name As String
Dim Dept As String
Dim Age As Integer
Name = Sheet1.Range("B1").Value
Dept = Sheet1.Range("B2").Value
Age = Sheet1.Range("B3").Value
Sheet2.Range("A2").Value = Name
Sheet2.Range("B2").Value = Dept
Sheet2.Range("C2").Value = Age
End Sub
Let's have a look at what happened in the background for these variables to work the way they did:
The Locals window will be visible at the bottom of the application:
Name = Sheet1.Range("B1").Value.
Take note that variables are not executable code but containers for data. There are no changes in the Locals window either because the highlighted line has not been executed yet.
Dept = Sheet1.Range("B2").Value
Age = Sheet1.Range("B3").Value
Sheet2.Range("A2").Value = Name
When we press F8 next, it will take the value Sue, which has been assigned to the Name variable, and place it in cell A2 of Sheet2.
Sheet2.Range("B2").Value = Dept
As with the previous line, the next variable, Dept, with the value HR assigned to it, will be placed on cell B2 of Sheet2.
Sheet2.Range("C2").Value = Age
The last variable, Age, with the value 28 assigned to it, will be placed in cell C2 of Sheet2.
The coding in this example can be improved upon because the macro will simply overwrite the values on Sheet2. In later recipes, we will write code to find the first open line under the data in Sheet2 and place it there.
If a variable is a line of VBA coding with the purpose of storing information on a temporary basis, a constant is a line of coding that stores information on a permanent basis.
Let's work with a practical example again.
Doing calculations in Excel is easy; you use a function or a formula and the problem is solved. But let's say you have to calculate the tax for products sold in a store on a daily basis. The data is not only on one spreadsheet, and people often randomly ask you to do these tax calculations.
As simple as it is to add a short formula, this is a waste of time. If you could click on a button with a macro assigned to it to do the calculation for you automatically, it would make your life much easier.
The tax rate can be stored as a permanent value in a constant and, depending on the VBA code, you can click on a cell and run the macro to calculate the tax for that specific item.
Open Excel and make sure that Book1 is active.
The steps to declare a constant are the following:
Sub Tax()
End Sub
Sub Tax()
Const Tax As Double = 0.1
End Sub
By typing Const, VBA will treat this line of code as a constant. After this keyword, we type the name of the constant – in this case, Tax. The data type is Double. Most importantly, the value for the constant is added in the same line.
Sub Tax()
Const Tax As Double = 0.1
ActiveCell.Value = ActiveCell.Offset(0, -1) * Tax
End Sub
The calculated value appears in cell B2.
Here is an explanation for each step as the macro was executed:
By clicking on another open cell, cell B3, you can run the macro again, this time without using Step Into:
To speed things up, you can add a button to Sheet1 and assign the Tax macro to it:
This way, it will be much easier to run the macro in order to do the calculations.
In this recipe, we will be investigating the different data types you can assign to variables and constants.
Open Excel and make sure that Book1 is active, and save the file as DatTypes.xlsm. Open the VBA Editor by pressing Alt + F11. In the VBA editor, click Insert | Module to create a new module in Book1. On the menu bar, click View | Locals Window, if the Locals window is not already active.
Sub Data_Types()
End Sub
Sub Data_Types()
Dim Small As Byte
Small = 75
Dim Big As Integer
Big = 3333
Dim Large As Long
Large = 800011100
Dim Yes As Boolean
Yes = True
Dim Dec As Double
Dec = 3.14159
Dim Text As String
Text = "MyName"
Dim DOB As Date
DOB = #12/25/1990#
Dim Price As Currency
Price = 24.55
'Variant
Dim Name
Name = Range("A1")
End Sub
It is important to assign data types to variables because it helps your code run faster, and also because memory is allocated more efficiently. In simple English, it means that you will be wasting memory if, for instance, you assign a Long data type if you could get away with an integer.
The following table explains the size of data types:
As a final remark, you need to understand that you can declare a variable without a data type. However, by doing that, VBA will automatically assign the Variant data type to that variable. An integer would have used 2 bytes of memory, while a variant would grab a minimum of 16 bytes per entry.
Make sure that you have a good understanding of this table and get into the good habit of always assigning data types.
In this recipe, we will be working with the range of effect, or scope, of variables.
Whenever you declare a variable in a module, you would expect that variable to at least have an effect within that module. You can also say you would expect your macro to work on the sheet where you created the macro, at the very least.
What has not been said before is that a workbook can accommodate any number of VBA modules and a module can accommodate any number of Sub and Function procedures. This information is merely academic.
This knowledge becomes important when you have more than one procedure in a module, several modules in the workbook, and more than just one worksheet in a workbook. The questions are: which macro will have an effect in which module, and is it possible for one macro to work in more than one module, or even in several sheets?
All depending on what you want to achieve with your macro, you can set the scope of a procedure with certain keywords. Let's see what those keywords are.
Open Excel and make sure that Book1 is active. Save the file as Scope.xlsm. Open the VBA Editor by pressing Alt + F11. In the VBA editor, click Insert | Module to create a new module in Book1.
Sub Proc_Level()
Dim Distance As Integer
Dim Number As Long
Dim Fraction As Double
Dim Name As String
End Sub
Sub Proc_Level2()
Dim Distance As Integer, Number As Long, _
Fraction As Double, Name As String
End Sub
This variable will be available in all procedures and all modules of the workbook.
Arrays are variables of a specific type. While a variable can store only one value at a time, arrays store multiple values, or elements. An array is therefore a group of variables sharing a common name. One example of an array would be the days of the week typed in a single column in Excel.
Like variables, arrays are also declared with a Dim statement. The rest of the line of code differs in the sense that with arrays, you have to specify the number of elements in the array.
In its simplest form, the elements consist of a first and last index number, separated with the To keyword, all in parentheses. This is known as a one-dimensional array, which stores a single line of values. Multidimensional arrays stores multiple rows and columns of values.
In this recipe, we will be discussing three types of arrays:
Open Excel and make sure that Book1 is active. Save the file as Arrays.xlsm.
On Sheet1, enter the days of the week in cells A1 to A7.
Open the VBA Editor by pressing Alt + F11. In the VBA editor, click Insert | Module to create a new module in Book1.
To create a one-dimensional array, do the following:
Sub StatArray()
End Sub
Sub StatArray()
Dim WeekArray(0 To 2) As String
End Sub
When you declare a variable, it is not always necessary to declare both the upper and lower index of the elements. The following declaration would mean exactly the same as the preceding one:
Dim WeekArray(2) As String
In this case, VBA assumes that 0 is the lower index. It must be mentioned that it is more reliable to declare both elements, though.
Sub StatArray()
Dim WeekArray(0 To 2) As String
WeekArray(0) = Range("A1").Value
WeekArray(1) = Range("A2").Value
WeekArray(2) = Range("A3").Value
End Sub
Sub StatArray()
Dim WeekArray(0 To 2) As String
WeekArray(0) = Range("A1").Value
WeekArray(1) = Range("A2").Value
WeekArray(2) = Range("A3").Value
Worksheets.Add.Activate
Range("A1").Value = WeekArray(0)
Range("A2").Value = WeekArray(1)
Range("A3").Value = WeekArray(2)
End Sub
Populating an array like this, with only three values in it, can easily be done manually. However, when you want to work with an array with hundreds, or even thousands, of values, this technique will clearly not be effective.
In a future recipe, where we will be explaining loops, this problem will be addressed. With loops, you can write code that can handle any number of elements in an array.
For a multidimensional array, do the following:
Sub MultiArray()
End Sub
Sub MultiArray()
Dim TableArray(0 To 6, 0 To 2) As Variant
End Sub
Sub MultiArray()
Dim TableArray(0 To 6, 0 To 2) As Variant
TableArray(0, 0) = Range("A1").Value
TableArray(0, 1) = Range("B1").Value
TableArray(0, 2) = Range("C1").Value
End Sub
Populating the rest of the rows can be done in the same manual way, but creating loops would once again be much more effective.
So far, we've been working with static or fixed arrays. In other words, we knew how many rows and columns there were in the Excel sheet and did not expect it to change. But what do we do if the data is not fixed? Let's say users have access to the data and have to add details. The ideal would be to use an array where the size can be changed while a program is running. That, by definition, is what a dynamic array is.
To declare a dynamic array, you simply leave the parentheses empty:
Dim MyDynamic () as Integer
Take the following steps:
Sub DynamicArray()
Dim Days() As String
End Sub
Sub DynamicArray()
Dim Days() As String
ReDim Days(6)
End Sub
By going through the steps for a one-dimensional array as they are executed in the VBA Editor, the process will become clear:
The steps for a multidimensional array can also be observed in the Locals window:
Once again, populating the rest of the row manually will become more and more laborious and time-wasting. In the Using Loops recipe in Chapter 9, Implementing Program Flow, we will show you how to populate multiple rows with great efficiency.
As with the two fixed arrays, it is best to see how it works in the Locals window:
Where the Days array was previously empty, there are now seven elements added.
We are not going to populate the values because it will be easier to do so with a Loop statement.
3.144.48.135