Chapter 24 Flashcards
(39 cards)
Visual Basic for Applications (VBA)
A programming language is a language with which we give instructions to a computer. Computers essentially ‘understand’ only a language made up of zeroes and ones. Such a language, in zeroes and
ones, is called a machine language. Zeroes and ones are hard for humans to read and interpret quickly. Therefore, we have a variety of languages which are more user-friendly and where we can use words used in normal human languages, such as English. Computer languages used by humans to write programs are sometimes called high-level languages. In contrast, a machine language is referred to as a low-level language.
Visual Basic for Applications (VBA)
When we write programs in a high-level language, we need to be able ‘translate’ this language to a machine language. This translation job is done by another computer program called a compiler. A computer
compiles the instructions (given in the high-level language) to zeroes and ones (understood by the computer).
Visual Basic for Applications (VBA)
In communicating (in any medium) humans may make errors that lead to the message being unclear. In other words, we need to follow rules for communication – such as using the right grammar and syntax. In the same way, we need to follow the rules of the language in writing a program in a given language. In this context, the compiler performs a useful function; as it translates from the high-level language to the low-level language, it checks to see that the instructions we are writing follow the correct syntax.
Visual Basic for Applications (VBA)
In the process of such translation, or compiling, the compiler also serves another useful function. It identifies errors related to grammar or syntax in the instruction and helps contribute to the accuracy of the
program we are writing.
Visual Basic for Applications
A number of high-level languages are available today; each has its own features and strengths. VBA is a high-level language. Its origins can be traced back to BASIC,
(Beginner’s All Purpose Symbolic Instruction Code). Microsoft introduced Visual Basic (VB) with a view to providing an easier programming environment. Visual Basic is a stand-alone language, in the sense that it
does not need another application within which it has to run. Using Visual Basic, we can create sophisticated software applications. Visual
Basic for Applications, as the name suggests, is a language that functions within an application or another software program. The main function of
VBA – in a given application – is to help us work with that application more efficiently.
We will use VBA in the context of Excel. However, VBA can also be used in many other Microsoft Office Applications such as Word, PowerPoint etc. A major advantage of learning VBA is that similar concepts are applied within other applications. Learning VBA in any one application opens up a portal to other programming environments that use VBA.
By learning VBA, you will be able to:
- use Excel more efficiently
- use Excel more effectively
- think through a problem more logically
- understand programming in other applications
What is needed from you
- You do not need to be a programmer or have prior programming experience
- You should be ready to put in a lot of time experimenting and practicing
- You should have the ‘DEVELOPER’ menu or tab on Excel. If you do not see a ‘Developer’ menu, you need to add this.
How to add the DEVELOPER tab
- FILE -> Options -> Customize Ribbon
- On the right hand of the dialog box, check DEVELOPER.
Where in the EXCEL is the VBA program or code
In Excel, as in other Microsoft Office applications, the visual basic code or program is stored in a ‘module’ in the Visual Basic Editor (VBE).
How to go to a module in the VBE:
- Keyboard: by pressing ALT-F11
- Mouse: DEVELOPER Ribbon -> Code group -> Visual Basic.
Visual Basic Editor (VBE)
Just as a workbook holds worksheets, the VBE is a ‘place’ that holds
- Modules: Modules contain the actual code or program. Modules are containers that hold one or more programs.
- Project Explorer: Just as the Windows Explorer shows what drives, folders, files are available, the Project Explorer shows what workbooks are open, what worksheets there are in each workbook, and what modules are there. Chances are that you will see files that you do not recognize. These are files used by Excel
- Properties Window: The Properties Window that shows the properties of the module that we are looking at.
Macros
A macro is a small program within an application such as Excel. Macros are sometimes also referred to as procedures. Macros can be created by the user for use in Excel (and in many other programs). A simple way to start understanding macros (or procedures or programs) is to record a macro. Just as a voice recording captures your voice, recording a macro in Excel captures your actions in Excel.
How to record a macro
- Click on the Developer tab. To the left, you will see a button for ‘Record Macro’. Click on this button. You will be asked for four things. Some of these are optional, but go ahead and get into the habit of providing all four items of information asked.
- First, provide a Macro Name. You can call it “FirstMacro”. (Note that the macro name should be one word, without spaces, and should not start with a number).
- Second, provide a Shortcut Key. (The Shortcut Key is a combination of CTRL followed by a letter. Just as clicking on the ‘play’ button on your voice recorder will play your voice, clicking the Shortcut Key will repeat your actions in Excel.)
- Third, provide a location to store the module (Should the module be stored in your current workbook, a new workbook, or a workbook called
Personal Macro Workbook? Usually you will store the macro in the current workbook.) - Finally, provide a description of what the macro is going to do.
Once you have provided this information, and click “Ok”, your macro will begin recording. Note that the ‘Record Macro’ on the Developer Tab has changed to ‘Stop Recording’. Your actions in Excel are now being
recorded.
Saving your Macro
As macros can be written for malicious purposes, there are usually security concerns around macros. For this reason, Excel 2013 requires a separate file type to indicate that the Excel file contains macros. Older versions of Excel – prior to Excel 2007 – had a 3-character file extension. Excel 2010 and Excel 2013 have 4-character file extensions.
When you try to save a workbook that contains a macro, Excel prompts you to save the workbook as a macro-enabled workbook.
If you choose to continue saving the workbook as the more usual .`xlsx file, the contents of the workbook will be saved, but the macro will be lost. The file extension .xlsm denotes a workbook containing a macro.
Naming your Macro
Just as with range names, we need to follow some rules when naming a macro.
The name:
- must begin with a letter
-cannot contain a period or a punctuation mark 0r special characters
- can include one or more underscore _ marks
- cannot have spaces
- cannot exceed 255 characters
- cannot use reserved words
Examples of Valid Macro names
- TotalRows
- total_rows_10
- Total_number_of_Rows
Examples of invalid macro names
- Total.Rows (contains a period)
- 5Rows (starts with a number)
- Total&Rows (includes special characters)
- Total Rows (Space not allowed)
Caution while copying and pasting from Microsoft Word to Visual Basic Editor
When copying and pasting from Microsoft Word to the Visual Basic Editor in the Integrated Development Environment, we need to be careful when copying quotation marks known as smart quotes. Smart quotes can copy over as symbols rather than as quotes. Running the macro will generate an error message.
Looking at the code in the macro
On the Developer Tab, click on the ‘Macros’ button. Below the large window with ‘Macro name’ is a smaller window titled ‘Macros in’. Choose ‘This Workbook’ from the drop down box. You will see the name
of the macro you recorded in the large window titled ‘Macro Name’. Click on FirstMacro. Then click on edit.
You will see something very similar to the following:
Sub FirstMacro()
‘ FirstMacro Macro
‘ My first macro
‘ Keyboard Shortcut: Ctrl+l
Range(“E5”).Select
ActiveCell.FormulaR1C1 = “Hello World!”
Range(“E6”).Select
End Sub
What do the lines in the code mean
VBA conveniently gives the words in the code different colors which makes it easy for us to read the code. Words in blue are reserved words, or keywords that mean specific things to Excel. For example, you cannot use the word ‘Sub’ as a macro name. Words in green are comments.
Comments are provided for the benefit of the user, and are not lines in the program itself. For example, the description of the program you provided is shown as a comment. Comments start with a single quotation mark. You can write anything here. Excel does not care what you write and will ignore any line that starts with a single quotation mark.
The first line in each macro begins with the word ‘Sub’ followed by the name of the macro and the first line ends with open and close parentheses like these (). The last line has the words ‘End Sub’. The entire program or macro has to be contained within the lines Sub, and End Sub. If you have any text before the ‘Sub’ line or after the ‘End Sub’ line, or Excel will indicate an error when you try to run the macro.
The line ActiveCell.FormulaR1C1 = “Hello World” indicates that you entered the words “Hello World” in the active cell. The active cell is simply the cell where the cursor is in Excel. FormulaR1C1 is Excel’s way of
referring to the value in that cell. The period ‘.’ separates the object from a property of the object; e.g., the cell-object is separated by a period
from the value-property. Just as you can say Car.Door to refer to the door of your car, or Car.Engine to refer to the engine of your car, you can say Activecell.FormulaR1C1 to indicate the value in the cell where your cursor is. The cell is considered an object (just as your car is an object). The characteristic (of value) is considered to be a property or attribute of the object (just as the car door is an attribute of the car).
Replaying (or running) the macro
Before you run your macro, it is important to remember that once an Excel macro is executed you cannot undo the results of the execution. In other words, CTRL-Z to undo will not bring the spreadsheet back to its pre-macro state. Hence, before you run a macro, it is a good idea to make a backup copy of your workbook.
Replay the macro. Go to any other worksheet in the workbook where you created the macro. Press the short cut key that you provided when you recorded the macro. The macro will enter “Hello World” in cell E5 in that worksheet. After it enters “Hello World” the macro will then activate cell E6 (because
that is where you went after you entered “Hello World”).
Objects
An object represents a building block in Excel such as a cell, a worksheet or a workbook. The Excel Object Model refers to a description of all the objects in Excel.
A group of objects is known as a collection. A collection is itself an object. You can think of The University of Texas at Dallas as an object
which is a collection of schools. Schools are collections of buildings. Buildings are collections of classrooms (and other rooms). Similarly, you
can think of the Excel application as an object that is a collection of different workbooks that you may have open at the same time. Each workbook is a collection of worksheets. Each worksheet is a collection of rows and columns.
Properties of Object
Properties are something that an object has. Properties describe the object. E.g., a car is an object. A car has the property of having one or more doors. Similarly, in Excel, the Range object has the property ‘Title’. That means that a range can have a title.
Properties define the characteristics of an object. A property can also define the way the object behaves. E.g., a cell can take on a value, a color, a border.
Methods
Methods do something to or with the object. A method is an action that can be performed on or with objects. For example, a car is an object. You can say Car.Door.Open to indicate ‘open car door’. (Note it is
not clear which door to open; but we can refine this further by saying Car.DriverSideDoor.Open). Similarly, you can say Range.Delete to say that the range should be deleted.
The Object Browser
When you are in the Visual Basic Editor (VBE), press F2 (function key F2) to see the Object Browser. The Object Browser shows the objects and the methods and properties (if any) associated with it. The green
symbol next to an item indicates that the item a method. The hand symbol indicates that the item is a property.
What are events in Excel
Events are various things that can happen in a program such as Visual Basic. Visual Basic programs can be structured around events. For instance, opening a workbook, activating a worksheet, choosing a particular cell, these are all events. We can write a program that is
triggered when an event happens.