srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming...

22
VBA Programming Basics The VBA programming language provides the tools needed to create solutions when the macro recorder can’t get the job done. VBA is such a powerful programming language that you can (if you have the programming ability) create a solution to virtually any problem you encounter in Excel. In fact you can completely customize Excel through VBA and you can even change the entire Excel interface. Object Oriented Programming VBA is a structured programming language where sentences (called statements) are constructed of building blocks such as objects, methods, and properties. These VBA statements are grouped in larger blocks called procedures. A procedure is a set of VBA statements that performs a specific task or calculates a specific result. The first step to learning how to create procedures is to learn about the building blocks. Objects VBA is an object-oriented programming language, which means the statements you create in VBA act on specific objects rather than begin general commands. Excel is made of objects that you can manipulate through the VBA statements. The entire workbook file is an object, an individual sheet is an object, a range within a sheet can be an object, and an individual cell is an object. There are many more types of objects, and as you see objects can be containers for (called collections) other objects. Collections Some objects are collections of other objects. For example, a workbook is a collection of all the objects it contains (ex. sheets, cells, ranges, charts, VBA modules, etc.). A VBA statement that makes reference to the workbook names “Loan Calculator.xls” would appear like this: Workbooks(“Loan Calculator.xls”) Methods A method is an action that can be performed on an object. Excel VBA objects are separated from their methods by a period. For example, if you wanted to save a particular file as part of a VBA program you could include the following sentence in the code: Workbooks(“Loan Calculator.xls”).Save Properties Properties are used to describe an object. Some properties are read-only, while others are read/write. These properties describe Excel objects. For example, an Excel workbook has a particular path on your hard drive or network where it is saved. That path is a property of the workbook. That path is read-only as it cannot be changed without saving the file to a different location. Properties are separated from objects by periods just

Transcript of srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming...

Page 1: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

VBA Programming BasicsThe VBA programming language provides the tools needed to create solutions when the macro recorder can’t get the job done.  VBA is such a powerful programming language that you can (if you have the programming ability) create a solution to virtually any problem you encounter in Excel.  In fact you can completely customize Excel through VBA and you can even change the entire Excel interface.

Object Oriented ProgrammingVBA is a structured programming language where sentences (called statements) are constructed of building blocks such as objects, methods, and properties.  These VBA statements are grouped in larger blocks called procedures.  A procedure is a set of VBA statements that performs a specific task or calculates a specific result.  The first step to learning how to create procedures is to learn about the building blocks.

ObjectsVBA is an object-oriented programming language, which means the statements you create in VBA act on specific objects rather than begin general commands.  Excel is made of objects that you can manipulate through the VBA statements.  The entire workbook file is an object, an individual sheet is an object, a range within a sheet can be an object, and an individual cell is an object.  There are many more types of objects, and as you see objects can be containers for (called collections) other objects.

Collections Some objects are collections of other objects.  For example, a workbook is a collection of all the objects it contains (ex. sheets, cells, ranges, charts, VBA modules, etc.).  A VBA statement that makes reference to the workbook names “Loan Calculator.xls” would appear like this:   

Workbooks(“Loan Calculator.xls”)

MethodsA method is an action that can be performed on an object. Excel VBA objects are separated from their methods by a period.  For example, if you wanted to save a particular file as part of a VBA program you could include the following sentence in the code: 

Workbooks(“Loan Calculator.xls”).Save

PropertiesProperties are used to describe an object.  Some properties are read-only, while others are read/write.  These properties describe Excel objects.  For example, an Excel workbook has a particular path on your hard drive or network where it is saved.  That path is a property of the workbook.  That path is read-only as it cannot be changed without saving the file to a different location.  Properties are separated from objects by periods just as methods are.  The following sentence will display the current path of the Loan Calculator.xls file in an onscreen message box: 

Msgbox Workbooks(“Loan Calculator.xls”).Path 

Note: Msgbox is a function.  Functions will be discussed later in this section. 

If you want to set a read/write property equal to something, it changes the current value of that particular object.  If you don’t set a read/write property equal to something, Excel will tell you the object’s current value.  For example, the following sentence will set the sheet name of the first sheet in the workbook to “Cover” 

Sheets(“Sheet1”).Name = “Cover”

FunctionsA VBA function is a lot like a workbook function in an Excel spreadsheet.  It performs a calculation

Page 2: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

and then returns the appropriate result.  Functions provide information that is useful in building VBA procedures.  In the previous example, the Msgbox function was used to display the path information on the screen.  

VBA Functions should not be confused with Function Procedures.  A Function Procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but a function can also return a value. A Function procedure can take arguments, such as constants, variables, or expressions that are passed to it by a calling procedure. If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A function returns a value by assigning a value to its name in one or more statements of the procedure.

ProceduresWhen you create VBA code inside an Excel workbook it will be stored as a “Module” within the workbook.  Unlike, Lotus 1-2-3 macros, these modules are not entered in cells but are still a part of the workbook files.  They can only be viewed by using the VBA Editor.

 

Code within a module is organized into procedures. A procedure tells the application how to perform a specific task. Use procedures to divide complex code tasks into more manageable units.  There are three types of VBA procedures: Sub, Function, and Property. 

The Insert Procedure Dialog Box 

The most common type of procedure is the Sub.  A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements that performs actions but doesn't return a value. A Sub procedure can take arguments, such as constants, variables, or expressions that are passed by a calling procedure. If a Sub procedure has no arguments, the Sub statement must include an empty set of parentheses.  The following is an example of a simple Sub: 

Sub Center_Across_Selection()

' Center_Across_Selection Macro          ' Macro recorded 4/19/2003 by Carlton Collins    With Selection        .HorizontalAlignment = xlCenterAcrossSelection        .VerticalAlignment = xlBottom        .WrapText = False        .Orientation = 0        .AddIndent = False

Page 3: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

        .ShrinkToFit = False        .MergeCells = False    End With    Selection.Style = "Comma"    Selection.Font.Underline = xlUnderlineStyleSingleAccountingEnd Sub

Variables and ConstantsDuring the execution of some VBA macros there will be times when information that is either gathered from the user, returned by a function, or defined by the programmer that must be stored temporarily for use later on in the macro.  Sometimes this information will change during the execution of the code and sometimes it will be static.  Variables and constants are used to store this type of information.  In the following macro CoName is a variable: 

Sub Add_Footer()    CoName = InputBox("Name your Company?", "Add Company Name to  Footer")    With ActiveSheet.PageSetup        .LeftHeader = ""        .CenterHeader = ""        .RightHeader = ""        .LeftFooter = CoName        .CenterFooter = ""        .RightFooter = "&N"    End WithEnd Sub 

Like a variable, a constant is a temporary holding place for some information that is used in a procedure.  However, as the name implies a constant never changes.  Constants must be declared.  A declaration statement in a VBA macro is used to define the value of a constant.  In the following macro the Company Name is declared in the first statement of the VBA code: 

Sub Add_Footer()    Const CoName = “Accounting Software Advisor”    With ActiveSheet.PageSetup        .LeftHeader = ""        .CenterHeader = ""        .RightHeader = ""        .LeftFooter = CoName        .CenterFooter = ""        .RightFooter = "&N"    End WithEnd Sub 

The company name is enclosed in quotation marks.  All literal text (this is what strings are referred to in VBA programming), which is placed in a procedure, must be surrounded by quotation marks.

- END -

Getting to grips with VBA basics in 15 minutes

Article contributed by Bill Coan

I can't turn you into a VBA expert but I can suggest a way to explore VBA that you may find helpful. Below, I've listed 22 steps that can be completed in approximately 15 minutes, assuming someone is kind enough to read them to you as you sit at your keyboard. If you have to read them by yourself and turn your attention alternately to the

Page 4: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

keyboard and back to the steps, then you may need a half hour or longer to complete the steps. Either way, the steps should give you a feel for what it's like to program in Word.

Before starting, launch Word, then press Alt+F11 to launch the VBA editor, and then maximize the VBA editor window.

Ready? Let's start:

1. In the VBA editor, choose Options on the Tools menu and make sure the following checkboxes are checked: Auto List Members Auto Quick Info

2. Press F7 to view a code window, if not already displayed.

Then type “Sub Test” and hit the enter key. The VBA editor will create a subroutine for you that looks as follows:

Notice that the cursor is already flashing inside the subroutine, ready for you to type a command

3. Click in the code window and type the following, making special note of the dot at the end of the expression:

ActiveDocument.

4. If you want to work on the active document (and who doesn't) then you have to start this way. (Think Jesus: No one gets to the father except through me!) When you type the "." at the end of the expression a list will pop up. This list is the most amazing guide you can imagine. Each item on the list is either a method or a property of the ActiveDocument or else it's an object unto itself that belongs to the ActiveDocument. For now let's deal with methods. Toward the end of this message we'll deal with properties. At the very end of the message, we'll deal with other objects besides the currently active document.

A method is something you can DO to the ActiveDocument, like print it out. The way to think is this: “I'm trying to do something to the active document as a whole, namely, print it. If I'm patient and scroll through this list, I'll almost certainly find a method that will do this for me.” When you first think this way, the word “method” will stick in your throat like a fishbone. Later it will feel more like burnt toast and later still it will feel like candy when you were young. Indeed, in this case, if you're patient, you will scroll far enough to encounter a method called PrintOut. Eureka! You know it's a method (as opposed to a property) because it has an icon next to it that looks like a green brick flying through the air and at this stage the whole concept of method makes you feel like throwing a brick.  Nice mnemonic, eh?

Let's give it a try. Since you've scrolled down and selected PrintOut, you can press Tab to accept it or you can double-click it right there in the list. Either way, your statement now looks as follows

5. So far so good. Most people easily get this far. But now what?

6. One possibility is that you're done. After all, you've specified an object (the active document) and you've selected something that you want to do to it (print it out). Indeed, if you're willing to let Word print out the document in whatever way it chooses, then you are done.

7. Another possibility is that you want to control how the print job will be carried out. In

Page 5: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

this case, you must provide some “arguments” (another fishbone, at first). Not to worry. To enter one or more arguments, all you do is type a space after the method and let the editor help you enter them. Arguments are equivalent to the choices you make in the Print dialog box. So go ahead, type a space after PrintOut, so your screen looks like this (the pipe character “|” represents your flashing insertion point after you've typed a space):

8. But wait! When you type the space, the VBA editor suddenly gets very helpful again, showing you something like the following:

9. Aha! Aha! These are the arguments for the PrintOut method. Most of them are immediately recognizable if you've ever paid attention to the Print dialog box. If you're wondering about one or more of them, simply press F1 and you'll call up a help topic that tells you all about each one of them.

10. Now that you can see all the arguments, you can enter values for as many of them as you desire.

One way to do this is to type the name of the argument and then a value, using “:=” to connect them and a comma to separate one argument/value from the next, like so:

ActiveDocument.PrintOut Background:=False, Copies:= 2

Another, boneheaded (in my opinion) way to do this is to enter values for ALL of the arguments, in which case you don't have to type the names of the arguments but you do have to account for ALL of them, as follows:

ActiveDocument.PrintOut False, , , , , , 2, , , , , , ,

11. Let's go with the named-argument approach:

ActiveDocument.PrintOut Background:=False, Copies:= 2

12. That wasn't so painful, was it? Now press F5 to run the subroutine. Or return to Word and choose Tools|Macro|Macros...|Test|Run. (Pressing F5 is easier!)

A quick review before we plunge on to properties. You think: “I'm trying to do something to the active document as a whole, namely, print it. So I start by typing “ActiveDocument.” and a list pops up. I scroll through the list and select the PrintOut method. Then I type a space and enter some arguments. In this case, I want background printing off and I want two copies, so I type the names of those arguments and values for each of them. I connect each argument name to its value by using “:=” because I'm part of the cognoscenti.”

Take a big breather here because now it's time to explore properties instead of methods . . .

13. Let's go back to our original assumption, namely, that you want to work on the active document as a whole. In this case, though, let's assume you want to change one of the properties of the document, rather than hit it with a brick.

14. Once again, click in a code window and type the following, making special note of the dot at the end of the expression:

ActiveDocument.

15. Remember, if you want to work on the active document (and who doesn't) then you

Page 6: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

have to start this way. (No one gets to the father except through me!) When you type the “.” at the end of the expression a list will pop up. This list is the most amazing guide you can imagine. Each item on the list is either a method or a property of the ActiveDocument or else it's an object unto itself that belongs to the ActiveDocument. For now let's deal with properties.

A property is a single characteristic. One of the properties of a document is its password. The way to think is this: “I'm trying to change a property of the active document as a whole, namely, its password. If I'm patient and scroll through this list, I'll almost certainly find a password property.” Indeed, in this case, if you're patient, you will scroll far enough to encounter a property called Password. Eureka! You know it's a property (as opposed to a method) because it has an icon next to it that looks like a finger pointing at a piece of information. Pretty useless mnemonic, eh?

Let's give it a try. Since you've scrolled down and selected Password, you can press Tab to accept it or you can double-click it right there in the list. Either way, your statement now looks as follows:

ActiveDocument.Password

16. So far so good. Many people easily get this far. But now what?

17. In this case, the next step is to specify a value for the property. To do this, all you do is type a space and an equals sign after the name of the property, so your screen looks like this (the pipe character “|” represents your flashing insertion point after you've typed a space):

ActiveDocument.Password = |

18. Since the VBA editor has no idea what value you want to use for a password, it can't offer any suggestions. Instead, you simply have to come up with an idea on your own and type it in, perhaps as follows:

ActiveDocument.Password = "billcoan"

That's it! That's it! Now press F5 to run the subroutine. Or return to Word and choose Tools|Macro|Macros...|Test|Run. (Pressing F5 is easier!)

When this statement runs, it will assign “billcoan” to be the password for the currently active document. You might wonder how you were supposed to know that the password had to be enclosed in quotation marks. Well, experience ought to be worth something, oughtn't it? In any case, if you had any question, all you would have had to do is position the cursor anywhere in the name of the property (“Password”) and press F1. This would display a help topic that tells you that a password requires a string, which is to say, a bunch of characters inside some quotation marks.

Take a big breather here because now it's time to explore objects other than the currently active document . . .Let's face it, the currently active document, as a whole, can hold our attention for only so long. After all, you can carry out only so many methods on it (printout, save, saveas, etc., etc.) and you can change only so many of its properties (password, grammar checked, spelling checked, etc., etc.).

But what about working on a particular part of a document, such as the first paragraph all by itself, or on a collection of parts, such as all the paragraphs? Here lies opportunity! After all, documents aren't just objects unto themselves; they're composed of hundreds of other, smaller objects. And you can work on each of those objects individually or as parts of collections.

Let's dig deeper and find out how.

19. The good news is that you can “reach” any part of a document that you want to work on by starting out as though you were going to work on the document itself. In other words, you can start as you almost always start. That is, once again click in a

Page 7: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

code window and type the following, making special note of the dot at the end of the expression:

ActiveDocument.

20. If you want to work on a part of the active document then you have to start this way. (Remember: No one gets to the father except through me!) When you type the “.” at the end of the expression a list will pop up. This list is the most amazing guide you can imagine. Each item on the list is either a method or a property of the ActiveDocument or else it's an object unto itself that belongs to the ActiveDocument. For now let's deal with objects that belong to the ActiveDocument.

An object is something that you can “work on” by applying methods to it or by changing its properties. Word documents contain lots of different types of objects. When multiple objects of the same type exist (or can exist) in the same document, they are treated as “collections.” For example, a word document has, or can have, multiple paragraphs. Each paragraph is an object. All of the paragraph objects, together, form the “paragraphs collection.”

The easiest document objects (and collections) to think about are paragraphs, words, and characters. The way to think is this: “I'm trying to work on an object that belongs to the active document, namely a paragraph. Since a document can contain more than one paragraph, I'll have to locate the collection of paragraphs and then specify the specific paragraph that I want to work on. If I'm patient and scroll through this list, I'll almost certainly find the collection.”

When you first think this way, the words “object” and “collection” will stick in your throat like a fishbone. Later it will feel more like burnt toast and later still it will feel like love when you hit puberty. Indeed, in this case, if you're patient, you will scroll far enough to encounter a collection called Paragraphs. Eureka! You know it's not a method because it doesn't have an icon next to it that looks like a green brick flying through the air. You don't think of it as a property, either, but you quickly find out that the VBA editor *does* think of it as a property. OK, OK. So one of the “properties” of a Word document is that it contains a collection of paragraphs. Great. So “Paragraphs” is a collection of paragraph objects and “Paragraphs” is a property of a Word document. This is confusing, so quit worrying about it. Focus on the list! Find the item you want to work on!

Let's give it a try. Since you've scrolled down and selected Paragraphs, you can press Tab to accept it or you can double-click it right there in the list. Either way, your statement now looks as follows:

ActiveDocument.Paragraphs

21. So far so good. Most people easily get this far. But now what? A major wrinkle, that's what! But hold on, it's easy to deal with. Since “Paragraphs” is a collection, you have to tell the VBA editor which paragraph you're interested in. You do this with a number in parentheses. For example, (1) refers to the first paragraph. Let's assume you want to work on the first paragraph in the collection. Type until your statement looks like this:

ActiveDocument.Paragraphs(1).

22. Guess what? You've just “drilled down” from the ActiveDocument object to the Paragraphs collection to the first Paragraph. That is, you've “reached” or “specified” an object that you want to work on. From here on out, life is easy. Why? Because working on a paragraph object is just like working on a document object. As soon as you type the dot after the object, the VBA editor shows you a list of all the methods, properties, and objects (or collections of objects) that belong to *your* object. Simply select the method that you want to carry out on your object, or select the property that you want to change, or keep drilling down by selecting an object or collection that belongs to your object. That's all there is to it.

A possible 23rd step would be to repeat Steps 1 -22 but replace all occurrences of

Page 8: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

“ActiveDocument.” with “Selection.” This allows you to drill down from the Selection object and discover the various methods, properties, and collections associated with the Selection object.

A possible 24th step would be to repeat Steps 1 -22 but replace all occurrences of “ActiveDocument.” with “Application.” This allows you to drill down from the Word application object and discover the various methods, properties, and collections associated with that object.

Excel VBA Course Notes: 1. Macro Basics(File: VBA01-Macros.xls)Using the Macro RecorderOpen Excel and the VBE (Visual Basic Editor). Unless it has been changed, the VBE window contains the Project Explorer window and the Properties window (these can be accessed from the View menu).

Project Explorer: Works like a file manager. Helps you navigate around the code in your workbook.

Properties Window: Shows the properties of the currently active object (e.g. Sheet1) of the current workbook (e.g. Book1).

Exercise 1: Recording a Macro.This exercise shows what happens when a macro is recorded and demonstrates the difference between recording absolute and relative references.

1. On an empty worksheet in a new workbook, select cell C10

2. Start the Macro Recorder with option to save macro in This Workbook. At this point the VBE creates a new Modules folder. It's quite safe to go and look at it - your actions won't be recorded. Click the [+] next to the folder and see that the VBE has places a module in the folder and named it Module1. Double-click the module icon to open its code window. Switch back to Excel.

3. Make sure that the Relative Reference button on the Stop Recording toolbar is NOT pressed in.

4. Select cell B5 and stop the recorder.

5. Switch to the VBE and look at the code:

Range("B5").Select

6. Now record another macro, exactly the same way, but this time with the Relative Reference button pressed in.

7. Switch to the VBE and look at the code:

ActiveCell.Offset(-5, -1).Range("A1").Select

8. Now record another macro, but instead of selecting cell B5, select a block of cells 3x3 starting at B5 (select cells B5:F7)

9. Switch to the VBE and look at the code:

ActiveCell.Offset(-5, -1).Range("A1:B3").Select

Page 9: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

10. Play back the macros, having first selected a different cell than C10 (for Macro2 and Macro3 the starting cell must be in row 6 or below - see step 11 below)

Macro1 - always moves the selection to B5Macro2 - moves the selection to a cell 5 rows up and 1 column to the left of the selected cell.Macro3 - always selects a block of six cells starting 5 rows up and 1 column to the left of the selected cell.

11. Run Macro2 but force an error by selecting a cell in row 5 or above. The macro tries to select a non-existent cell because its code is telling it to select a cell 5 rows above the starting point, and that's off the top of the sheet. Press Debug to be taken to the part of the macro that caused the problem.

NOTE: When the VBE is in Debug mode the line of code that caused the problem is highlighted in yellow. You must "reset" the macro before you can proceed. Click the Reset button on the VBE toolbar or go to Run > Reset. The yellow highlighting disappears and the VBE comes out of Debug mode.

12. It is important to try and anticipate user error like this. The simplest way is to modify the code to simply ignore errors and move on to the next task. Do this by adding the line…

On Error Resume Next

… immediately above the first line of the macro (underneath the line Sub Macro1()

13. Run Macro2 as before, starting too high on the sheet. This time the line you typed tells Excel to ignore the line of code that it can't execute. There is no error message and the macro exits having done all it can. Use this method of handling errors with caution. This is a very simple macro. A more complex macro would probably not perform as expected if errors were simply ignored. Also, the user has no idea that something has gone wrong.

14. Modify the code of Macro2 to include a more sophisticated error handler thus:

Page 10: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

Sub Macro2() On Error GoTo ErrorHandler ActiveCell.Offset(-5, -1).Range("A1").Select Exit SubErrorHandler: MsgBox "You must start below Row 5"End Sub

15. This time the user is presented with a dialog box when something goes wrong. If there is no error the line Exit Sub causes the macro to finish after it has done its job - otherwise the user would see the message even if there were no error.

Improving Recorded MacrosThe good way to learn the basics of VBA is to record a macro and see how Excel writes its own code. Often, though, recorded macros contain much more code than is necessary. The following exercises demonstrate how you can improve and streamline code that has been produced by a recorded macro.

Exercise 2: Improving on Recorded MacrosThis exercise shows that when macros are recorded, often more code is generated than necessary. It demonstrates the use of the With statement to précis the code.

1. Select any cell or block of cells.

2. Start the macro recorder and call the macro FormatCells. The Relative References setting will not be relevant.

3. Go to Format > Cells > Font and choose Times New Roman and Red.Go to Patterns and choose Yellow.Go to Alignment and choose Horizontal, CenterGo to Number and choose Currency.

4. Click OK and stop the recorder.

5. Click the Undo button (or Ctrl+Z) to undo your changes to the worksheet.

6. Select a block of cells and run the FormatCells macro. Note that it can not be undone! Type in the cells to check the result of the formatting.

7. Look at the code:

Sub FormatSelection() Selection.NumberFormat = "$#,##0.00" With Selection .HorizontalAlignment = xlCenter .VerticalAlignment = xlBottom .WrapText = False .Orientation = 0 .ShrinkToFit = False .MergeCells = False End With With Selection.Font .Name = "Times New Roman" .FontStyle = "Regular" .Size = 10 .Strikethrough = False

Page 11: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

.Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ColorIndex = 3 End With With Selection.Interior .ColorIndex = 6 .Pattern = xlSolid .PatternColorIndex = xlAutomatic End WithEnd Sub

Page 12: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

8. Note all the extra instructions that have been recorded. Delete lines of code so that only the following remains:

Sub FormatSelection() Selection.NumberFormat = "$#,##0.00" With Selection .HorizontalAlignment = xlCenter End With With Selection.Font .Name = "Times New Roman" .ColorIndex = 3 End With With Selection.Interior .ColorIndex = 6 End WithEnd Sub

9. Run the macro to test the edited code. It still works as before.

10. Now modify the code even further:

Sub FormatSelection() With Selection .NumberFormat = "$#,##0.00" .HorizontalAlignment = xlCenter .Font.Name = "TimesNewRoman" .Font.ColorIndex = 3 .Interior.ColorIndex = 6 End WithEnd Sub

11. Test the macro. Everything still works and the code will run much faster.

12. Try recording the same macro using toolbar buttons instead of going to the dialog box:Change the Font to Times New RomanChange the Font Colour to RedChange the Fill Color to YellowClick the Center buttonClick the Currency button

13. Look at the code. You still get lots of stuff that you don’t necessarily want. Excel is recording all the default settings. Most of these are safe to delete.

14. Experiment with editing directly into the code to change colours, the font, the number format etc.

Exercise 3: Watch a Macro Being RecordedThis exercise shows that you can learn by watching the macro build as it is being recorded. It is also an example of when sometimes the With statement isn’t appropriate.

1. Open the file VBA01.xls.

Whilst this worksheet is visually OK and can be understood by the user, the presence empty cells can cause problems. Try filtering the data and see what happens. Go to Data > Filter > Autofilter and filter by Region or Month. It is clear that Excel does not make the same assumptions that the user does. The empty cells need to be filled.

Page 13: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

2. Tile the Excel and VBE windows (vertically) so they are side-by-side.

3. Select any cell within the data. If it is an empty cell it must be adjacent to a cell containing data.

4. Start the macro recorder and call the macro FillEmptyCells. Set to record Relative References.

5. In the VBE window find and double-click the module (Module1) for the current workbook to open the editing pane, then switch off the Project Explorer window and the Properties window (only to make space).

6. Record the new macro as follows:

Step 1. Ctrl+* (to select the current region)Step 2. Edit > Go To > Special > Blanks > OK (to select all the empty cells in the current region)Step 3. Type =[UpArrow] then press Ctrl+Enter (to place your typing into all the selected cells)Step 4. Ctrl+* (to select the current region again)Step 5. Ctrl+C (to copy the selection - any method will do)Step 6. Edit > Paste Special > Values > OK (to paste the data back into the same place but discarding the formulas)Step 7. Esc (to come out of Copy Mode)Step 8. Stop Recording.

7. Look at the code:

Sub FillEmptyCells() Selection.CurrentRegion.Select Selection.SpecialCells(xlCellTypeBlanks).Select Selection.FormulaR1C1 = "=R[-1]C" Selection.CurrentRegion.Select Selection.Copy Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _ False, Transpose:= False Application.CutCopyMode = FalseEnd Sub

8. Note the use of the space-and-underscore “ _” to denote the splitting of a single line of code on to a new line. Without this Excel would treat the code as two separate statements.

9. Because this macro has been recorded with well thought out commands, there is little unnecessary code. In the Paste Special everything after the word “xlValues” can be deleted.

10. Try out the macro. Then use the AutoFilter tool and note the difference.

MACROS

INTRODUCTION – RECORDING A MACRO

Below are the instructions to recording a macro. Read through the instructions, and then complete the activities.

Page 14: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

1. Open a new blank document in Word.2. To create a macro we must first start the recording. From the Tools menu select Macro,

then Record New Macro.3. First we must name our macro. Use your initials (to distinguish yours from others who might

use the same computer) and a brief word or two. The Store macro in option allows you to store the macro in the Normal.dot template or in the current document. Using the default setting (Normal.dot) will allow us to apply the macro to any Word document. Therefore we will always store macros using the default setting.

4. Give a brief description of the macro under Description so you know what the macro is for if you want to use it again later.

5. Click OK when finished and the Stop Recording Macro toolbar will automatically appear. The Stop button will turn off the macro and automatically save the macro. The pause button will allow you to pause the macro to perform a task and then start it again when finished.

6. The next step is to insert the commands you would like the macro to perform. You would then key in the information you want the macro to repeat. Macros are code based which means it does not like mouse clicks, the scroll bars and any quick keys on the toolbars. All commands must come from the Menu bar or use their keyboard equivalents.

a. Remember the macro will perform each step in the order you do it, so do it carefully.

b. When recording your macro make your selection using the Menu bar (File, Edit, Insert, etc) NOT the toolbars because it will not become part of the macro. For example, if you wanted a title to be bold and centered use Format on the Menu bar, not the quick keys on the toolbars.

7. Click the Stop Recording button on the Recording Macro toolbar. It will automatically save.8. Open a new blank document. 9. Open the Macros (Tools – Macro – Marcos)10. Click on the macro name. Click Run.

ACTIVITY #1 – RECORDING A MACRO

In this activity we will create a macro that can be used as the beginning lines of an inter-office memo.

1. Open a blank document in Word.2. Turn on the Record New Macro function.3. Name the macro xxletter1 (xx represents your initials).4. Under Description, type the following: Opening lines for office memo. Click OK to start

recording the macro.5. Before entering any data, change the line spacing to double spacing, and then press Enter

four times.6. Enter the following information, bolding all the titles as shown:

TO: All Office Staff

Page 15: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

FROM: {Your Name}

DATE: {Current Date}

SUBJECT:

7. Insert time and date automatically on the dateline. Remember to use the menu bar, not the quick keys. Turn off the bold function after the subject line, press enter twice and set the line spacing back to single.

8. Click the Stop Recording button on the Recording Macro toolbar.9. Close the document without saving.10. Open a new Word document. 11. Run the macro you just created. Tools – Macro – Macros – (Select macro to be run) xxletter1

– Run.

ACTIVITY #2 – PARTY TIME

You are going to make party invitation for your 5 year old son or daughter. The invitation you are making is more of an FYI for the parents of all kids invited to the party. Instead of completing the same tasks and commands over and over again, you decide to make a macro.

Your macro must include the following information:

To, From, Date and Subject lines. Same or similar to the above. The To: line will be left blank, but the From, Date and Subject lines should be filled in with the appropriate information.

Under the Subject line, include a brief schedule of events, times and places that will be taking place that day. Include any other important information you would like the parents to know.

Close the invitation with your name and phone number so parents can call if they have any questions or concerns.

Save as party_1

Page 16: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

ACTIVITY #3 – INSERTING A TABLE USING A MACRO

Any repetitious tasks that you will be performing can be recorded, saved and stored as a macro for later use. Tables, which can take some time to create, can be saved as macros.

1. Open a new Word document. Name it xxtable, use the default setting under Store in, and give it the description of (Your Name’s) Table.

2. Begin recording a macro.3. Insert a 3 column, 4 row table. Remember to use the Menu bar. (Table – Insert – Table)4. Change the width of the borders to 6-point. (Table – Table Properties – Borders and shading

– Width)5. Shade the table using Style 25%. (Table – Table Properties – Borders and shading – Shading

(tab at the top) – Style – 25%)6. In cell A1, type ‘(Your Name’s) Table’s.7. Stop the macro and close the document without saving.8. Open a new Word document and run the macro.

ACTIVITY #4 – CAFETERIA MENU

You are the chef in the school cafeteria and use a table in Word to create your daily menu specials. Instead of re-creating the same table with the same title over and over again, you decide to record a macro.

The macro must include a 2 column, 6 row table with the following information:

The cafeteria name, merged, centered and bolded at the top, with a background colour of your choice.

Headings for each column that include the price of each menu item and the name of each food item.

The cafeteria always has one daily lunch special. So within your table make sure to enter the title ‘Daily Special’ into a cell of your choice. Make sure you leave the cell to the right of the ‘Daily Special’ blank because the item and price will change each day

Fill in the rest of the table with food items and prices of your choice. These are items that will not change daily. These items the cafeteria sells everyday for the same price.

Save as chef_1 when complete.

.

Page 17: srujana-shiva.netsrujana-shiva.net/Tutorials/VBA/VBAProgrammingBasic… · Web viewVBA Programming Basics

Button Macro – The Toolbars Button

Another way to run a macro is from a button assigned to a toolbar. To create this kind of macro, name the macro then click on the Toolbars button under the Assign macro to heading. The Customize dialog box will appear. Using the left mouse button, click and hold the macro. Drag and drop it to the very left of the Standard Toolbar. The button should appear on the toolbar. Click Close on the Customize dialog box. The Stop Recording macro toolbar appears and you can begin recording your macro. Click the macro button on the toolbar to run the macro when you wish.

ACTIVITY #5 – TOOLBARS

Redo activity #1 or #3 using the Toolbars Button.

Button Macro – The Keyboard Button

Similar to the Toolbars button, the Keyboard button will allow you to run a macro from a set of assigned keystrokes.