21
Objects, Debugging & Programming Tips Conestoga College © v.1.4 Peter Komisar reference: 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad This note has been generated for private academic use and is not meant to be published - PK Before demonstrating more features of Excel application we should do a canonical 'Hello World' in Excel. The basic module syntax, we have seen is the Sub keyword followed by the name of the macro and a pair of closed round braces. The module is ended with a closing 'End Sub' word combo. We have enclosed a comment in the empty sub, so technically it is not quite empty. From a programming view the comment is ignored. It is there strictly to communicate information about the code to the viewer. The Sub term is an abbreviation of 'sub-routine' which is an old term that describes a section of code that runs within a computer process. Example of An Empty Module with a Comment Sub EmptyMacro() ' empty sub, just a bun! End Sub There are many ways to do 'Hello World'. Using the Value function with the ActiveCell makes for an easy to understand example. “Hello World in Excel” Sub HiEx() ActiveCell.Value = "Hi Ex" End Sub A common way 'Hello World' is often shown in Excel makes use of the MsgBox method to put the text into a pop-up box. You can also use a statement like Range(A1:C1).FormulaR1C1=”Hello World in Excel”. (We look at the Range object next week.)

Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Embed Size (px)

Citation preview

Page 1: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Objects, Debugging & Programming Tips

Conestoga College © v.1.4 Peter Komisar

reference: 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy SyrstadThis note has been generated for private academic use and is not meant to be published - PK

Before demonstrating more features of Excel application we should do a canonical 'Hello World' in Excel.

The basic module syntax, we have seen is the Sub keyword followed by the name of the macro and a pair of closed roundbraces. The module is ended with a closing 'End Sub' word combo.

We have enclosed a comment in the empty sub, so technically it is not quite empty. From a programming view the comment is ignored. It is there strictly to communicate information about the code to the viewer.

The Sub term is an abbreviation of 'sub-routine' which is an old termthat describes a section of code that runs within a computer process.

Example of An Empty Module with a Comment

Sub EmptyMacro()' empty sub, just a bun! End Sub

There are many ways to do 'Hello World'. Using the Value functionwith the ActiveCell makes for an easy to understand example.

“Hello World in Excel”

Sub HiEx()ActiveCell.Value = "Hi Ex"End Sub

A common way 'Hello World' is often shown in Excel makes use of the MsgBox method to put the text into a pop-up box. You can also use a statement like Range(A1:C1).FormulaR1C1=”Hello World in Excel”. (We look at the Range object next week.)

Page 2: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

From the 'Hello World' code we can put in place our first rudimentsof the VBA language. First we can state the basic form of the moduleas follows.

Module Form

Sub Module_Name( )

End Sub

We also have seen that the basic comment form is a line started with a single apostrophe.

Comment Form

' this is a comment is VBA

Object-Oriented Programming in VBA

VBA is described as an object-oriented programming language, where related properties and functions are encapsulated together within a class.In proper 'OOP' Properties and Functions of a class are referred to as 'class members'.

Class Members

• Properties• Functions ( aka Methods )

// later events will be added

When functional copies of the class template are created, 'instances' or usable copies of this class are called objects of the class. VBA has a createObject function that can be used to create or construct objects of a class.

// three identical sheets are objects of the sheet class

An example of objects of a class are the three identical sheets that are created when a new Workbook is created in Excel. They are differentiated by their name, ( or perhaps their order number as part of a collection. )

From a practical point of view, the methods and properties that belong toan object of a class will always be referenced via a suffixed period) after the name of the object in which the properties and functions are defined as members.

Page 3: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

In the following example, the class is called ActiveCell. It has a property calledvalue defined for it, really in it, called Value. So we access the Value property via the period, formally called the dot operator. Here the string value “Hi Ex” isassigned to the property Value.

Example // from our HelloWorld Sub above

ActiveCell.Value = "Hi Ex"

The following diagram will help to visualize the object-oriented programming model. Think of the Sheet class and the objects as being Sheet1 Sheet2 Sheet3 etc.

Diagram of the VBA Object Model

Now we can pick up the story line from the textbook here.

Objects and Object Collections

Because many of the objects used in Excel are used in multiples, Excel uses an easy naming formula to refer to Collections or groups of objects.

Example

A collection of the Row objects becomes Rows.A collection of the Column objects becomes Columns.

Page 4: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

The basic formula is any object in a collection is suffixed with the letter 's' to signify a plurality of the object.

Object → Collection Version → Object(s)

Consider a collection of three cells. You might put a value into each of these cells by name or by index. In the following example the Sheets of a workbook are renamed based on numerical referencing while, in the final line of code, one sheet of the collection is referenced by name.

Example Referencing an Object in a Collection by Name // need a book with 3 sheets

Sub M_Referencing()

' M_Referencing Macro Sheets(1).Name = "S1" Sheets(2).Name = "S2" Sheets(3).Name = "S3" Sheets("S3").Select

End Sub

Using Methods

While properties are thought of as atttributes or characteristc aspects ofa class, the term function or method is used to describe an action that aclass can perform.

If we had a class Bird that could do something like fly and this was coded in VBA the syntax would be as follows.

Method or Function Reference Example

Bird.fly

Assigning Values to Parameters of a Method // parameters to methods are like adverbs

Now what if extra properties regarding how a bird flies are needed.Perhaps fly is designed to take two directions. The following exampleshows how two values passed to what are calle 'parameters' of a a VBA method.

Page 5: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Passing Parameters into VBA Methods with Properties Overtly Stated

Bird.fly Direction1:=”South” Direction2:=”West”

// this supposes two parameters have been defined in the fly method.

The colon followed by an equal sign is used in VBA to assign values to method parameters.

Colon Equal Sign Combo Is Used For Overtly Assigning Method Parameters

Parameter_Name := Parameter_Value

VBA also allows passing in parameters without stating which property is being addressed. In this form, the order in which properties are passed in is significant. The following is an equivalent way of doing the same function call we exampled above.

// this is too much information without examples in my view but we proceed as // the text leads us. Just remember these are rules associated with a class action // part called the class methods or functions.

Passing Parameters into VBA Without Stating Properties // order is significant

Bird.fly ”South” ”West”

Rule: You are allowed to start without naming parameters and thenswitch to naming parameters. Once you start naming them, you mustcontinue with this style for subsequent parameters.

Passing Parameters into VBA Without Stating Properties // order is significant

Bird.fly ”South” Direction2:= ”West”

So why would you do this?

A hypothetical example, a developer might wish to state a value forthe first two parameters of a method, accept the default for the third and fourth parameter but wish to specify the fifth, something like the following.

Example

Statements.formulate “Provincial” “HST” Fifth_Parameter:=”Sub-Total”

Page 6: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

// in this example the first two parameters are specified, two are left to default // values and the fifth is specified

More on Functions Later

The above example most would agreed is not really using good form. As a rule, one should try to code in a consistent fashion that is easy to read and understand. In the above example overtly stating all thevalues would make for easier maintenance.

We investigate how to build functions later.

Property & Function Referencing Are the Same, Both Use the Dot Operator

Properties of the class are referenced the same way as functions via what is commonly called 'the dot operator', represented by the period symbol. If the bird had a property size with the value 'big', this property would be expressed as follows.

Property Reference Example

Bird.size // to reference the value stored in the property 'size'.

To assign a property value for an property object the plain equal sign is used.

Example

Bird.size = 7 // if the property is 'read-only' an assignment can't be made

Top-Level Excel Objects

There are a huge number of Excel objects which we will survey shortly in the object browser. Some of 'top-level' objects are listed below just to get a feel for the organization of objects in Excel.

Major Top Level Excel Objects

• Application• Workbooks• Sheets • Worksheet• Range

Page 7: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Application

The application object refers to the Excel context in which the Macros run. It is not too often that this top level object will be referenced.

A few examples of the Application object are the width and height properties as well as the property that controls whether the formula toolbar shows.

Run the following macro, then change the values of the three properties to see the effect. The width and height control the size of the window that Excel runs in. Notice the formula bar disappears when the property is set to false.

Example Showing Three Properties

Sub App_Props()Application.Width = 900Application.Height = 700Application.DisplayFormulaBar = TrueEnd Sub

Workbook(s)

The Workbook is a single instance of Excel. The line of code in the following macro add another running instance of Workbook.

Example

Sub M_Add_A_Workbook()Workbooks.AddEnd Sub

WorkSheet

WorkSheet is another object in the Excel library. It has methods toadd a sheet before and after a given sheet. In the following example the name of the sheet is changed.

Example Showing a Sheet Renamed

Sub M_Name_That_Sheet()Worksheets("Sheet1”).Name = "Primary Page"End Sub

Page 8: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Range

The Range object is used to represent a sequence of contiguous cells, (that is, cells next to each other, either vertically or horizontally.) This object permits targeting some action on an individual cell or a collection of cells.

The Range object is one of the most used objects in VBA code. Rangesthemselves are specified by declaring the first cell in a range followedby the last cell, separated by a colon.

Following are a few Range examples.

Example of Range objects being used in a Macro

Sub M_Ranging() Range("A1:A3").Value = "XXX" Range("B4:B6").Value = "OOO" Range("C7:C9").Value = "XXX" Range("A10:D10").Value = "---" Range("A10:D10").Font.Bold = TrueEnd Sub

Cells

Cells are are listed as 'properties' of the Range object. The Cell and the collection Cells represent the 'atoms' of the Excel system. Cells can execute many useful methods.

To select all cells we make a call on the Cell object.

Example // to select all

Cells.Select

Also individual cells can be addressed by index and valuesattributed to those cells via the Value method.

Cell Example // note all cells have been selected

Sub Celly()Cells(1, 1).Value = "One One"Cells(3, 3).Value = "Three Three"Cells(5, 5).Value = "Five Five"Cells.SelectEnd Sub

Page 9: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

The above discussion has been aimed at providing an orientation to the object-oriented approach used in Excel and VBA .

Now back to the VBA environment for a while.

Use F1 to Find Anything

The VBA Help files is described as an indispensable tool for writingVBA code. VBA help topics is not installed by default.

Installing VBA Help Topics

The text supplies the following stategy to to see if Help is installed. A little HelloWorld is created and one of the components tested tosee if there is help for it.

• Open Excel • Switch to VB Editor ( Alt+F11) • select Insert → Module• type Sub Hello( )

MsgBox “Greetings”End Sub

• Place cursor in word MsgBox• Press F1• if Help is installed info comes up for 'MsgBox'

If help is not installed it can be with the original CD or by the administratorgranting permission to the install folder.

Go to 'custom install' and select VBA help files.

By inserting the cursor in any keyword and pressing F1 informationcan be obtained for that element.

Note: Pressing F1 takes you to the online version of Help. On that page there may be a link to the computer based help files, so there is a workaround in the event thathelp is not installed on your version of Excel.

Review of the Recorded Code

Following is a copy of the macro recorded in the first assignment. Now that a cursory tour of VBA object syntax is completed, more can be said about this code.

Page 10: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Import Invoice Macro Code

Sub M_Invoice_Import()' M_Invoice_Import Macro ChDir "C:\Documents and Settings\Peter\My Documents\VBA\VBA2010Files" Workbooks.OpenText Filename:= _ "C:\Documents and Settings\Peter\My Documents\VBA\VBA2010Files\invoice.txt", _ Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _ xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _ Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 3), _ Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1)), _ TrailingMinusNumbers:=True Selection.End(xlDown).Select Range("A11").Select ActiveCell.FormulaR1C1 = "Total" Range("E11").Select ActiveCell.FormulaR1C1 = "=SUM(R[-9]C:R[-1]C)" Range("E11").Select Selection.AutoFill Destination:=Range("E11:G11"), Type:=xlFillDefault Range("E11:G11").Select Range("A11:G11").Select Selection.Font.Bold = True Range("A1:H1").Select Selection.Font.Bold = True Cells.Select Selection.Columns.AutoFitEnd Sub

Placing the cursor in the OpenText method and pressing F1 shows the documentation for this method.

The following concise definition for what the method does is provided.

OpenText Method - the method “loads and parses a text file as a new workbook with a single sheet that contains the parsed text-file data.”

A fine point, you can see in the documentation that only one argument,the file name is required and the rest are optional.

The text points out that while the optional Startrow parameter may safelybe left out as the default yields the first row which is usually where you will want the page to begin.

Origin on the other hand, if not specified will use the origin used last in Excel which may be a character set from a totally different language.

Page 11: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

VBA Constants

An example where a parameter is fixed to a constant value can beseen with the DataType parameter. In the code above it is set to xlDelimited. The xl prefix is used to denote constants in Excel.

Constant Values Available for DataType

• xlDelimited // has the value 1

• xlFixedWidth // has the value 2

The Immediate Window

To see what values are stored in these constants, go to the VBEditorview of the code and Press Ctrl + G. This brings up the Immediate Window.

Type 'print xlDelimited' then enter. Then type 'printXlFixedWdth' and press enter. You will see the constants store the integer values 1 and 2 respectively.

Regarding the Help Context & Versions

Unfortunately, the Help context does not supply an indicator of whethera particular element is new to a particular version of Excel. This meansbackwards compatibility will need to be tested.

The OpenText Method & the Text Import Wizard

You can see on pages 42 through 44 that the OpenText method doesthe same actions as the Text Import Wizard. Clicking the Advancedbutton in the third stage of using the wizard allows changing the defaultsettings for Decimal and Thousands separators.

.More than one Item with Same Name in the Libraries

Clicking the End word in the line Selection.End(xlDown).Select will show two entries when Help is entered via F1. One is in the VBA library and the other is in the Excel library.

In the recorded macro the one in the Excel library is being used.

Page 12: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

In VBA, Properties can Return Objects

In the line 'Selection.End(xlDown).Select' a method is called on a parameter. The property End has a method, 'Select' called on it that returns a Range object.

In object-oriented programming you usually make method calls on objects not parameters. Then again, in purer programming languages, there is a mantra, 'Everything is an object, even literal numbers like 4 or 7. So if we think of parameters as objects in their own right, we can rationalize this from an OO point of view.

Selection Too Is A Property

If we were to check help on 'Selection' we would find it too is aproperty.

Not visible but implied is the fact that Selection is called on theApplication object. This isn't overtly stated when VBA is workingin the Excel object model.

Example

Application.Selection is the same as Selection

// in the latter the first call is automatically made on behalf of the user

The Debugging Tool

The Debugging Tool allows you to 'step through' code one lineat a time.

• → Developer• → VB Editor• → open a macro • (with cursor in code area )• → click Debug or press F8• → click Step Into

// You can also 'step in' from the Macro icon

Page 13: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Break Mode

Now you are in 'break' mode.

• The line about to execute is highlighted in yellow. • Press F8 to execute the next line of code & move to next line• Toggle via Alt+Tab

• to test the output up to this point toggle to Excel view

// See page 47 tip for displaying spread sheet output and code

If you hit a problem you can reset the debugger by hitting Run → Resetor hitting the Reset button on the toolbar. (The little blue square )

Divide and Conquer With Break Points

If your macro is big, as in hundreds of lines, you may not want to step through a line at a time. In this case you can set break points.

To Set a Break Point

• Click the gray line to the left in the VB editor at the line you wish to set a break point at.

• A brown ball appears with highlighting.

• Select Run → Run Sub → or

• press F5

The program executes and stops just before the break point.

To Remove a Break Point

• click the brown ball or

• select Debug → Clear All Breakpoints or

• press Ctrl+Shift+F9

Page 14: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Moving Back and Forth Through Code

Grab the yellow arrow with the mouse and move it up or down through the code statements.

Avoiding Stepping Through Each Line

At a loop that iterates scores of times, you wish to avoiditerating it, (by pressing F8) just to get to the line after it.

• Click the cursor on the line you wish to run to. • Then press Ctrl+F8

or• Debug → Run to Cursor

More Uses for the Immediate Window // see text at bottom of page 50

Press Ctrl+G to open the Immediate Window

The question mark abbreviates the print command. Type and press enter, one command at a time.

Examples // commands appear not to be case sensitive

?Selection.Address → $E$11 ?selection.value → 0?activesheet.value → invoice

Command Set in Immediate Window Applies to Subsequent Steps

Pressing F8 to execute the next statement and then placing the cursor at the end of the line of code in the Immediate Window and pressing enter will tack on the next return value with reference to the new line of code stepped into.

Step through the code line 'Cells.Select and cursor to the end of Selection.address command and press enter. You see the large range of addresses that correspond to a whole sheet of cells being selected.

Example Address Output on the Cells.Select command

$1:$1048576

Page 15: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Switch the command to selection.address.rows.count and you see that each address corresponds to a Spread sheet row.

Select.Rows.Count Output

1048576

Summary of Command Used in Immediate Window

• Print.• ActiveSheet.Name• ActiveCell.Address• ActiveCell.Formula • ActiveCell.Value• Selection.Address

To demonstrate ActiveCell formula from the above list, execute the line with the Sum in it in the Invoice macro, (in other words press F8 so yellow highlight is in the next line of code. Then the following output shows.

ActiveCell.Formula Output

=SUM(E2:E10)

// The Active Window is closed with the X symbol and opened with Ctrl+G

Hovering to Invoke Tooltips

Hovering over an expression that has a return value for a few seconds should raise a tooltip that gives the value that that expression evaluates to. ( This didn't work for me on my home version! Apparently there is a buggy 'not responding' mode. )

If your tooltips is working and some lines do not seem to respond this may be normal as the line in question may not evaluate to a value.

Excel has a window to monitor code called a 'watch'.

“The Watch Window makes it convenient to inspect, audit, or confirm formula calculations and results in large worksheets. “ - Microsoft Support Site

Page 16: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Using a Watch Window to Show Selection Addresses

• in a macro select Debug → Add Watch• enter Selection.Address in window• Enter Step mode ( select Debug → Step Into )• Step through code via F8 • notice Selection Addresses in Watch Window

A watch can be set to traverse the code and only stop where a significant change has occurred to the property in question. Follow the following procedure to set up breakpoints in a watch.

Setting Breakpoints in a Watch

• right click the line of code in the watch• click Edit Watch• change radio buttom selection to• Break when value changes• (close out Invoice.txt if that is what is running as your sample)• press F5

Watches on Objects

Watches can also be used to monitor objects.

Monitoring an Object in a Watch

• right click the line of code in the watch• click Edit Watch• drop ' .Address' from the end of Selection so

just the object Selection shows• Step into a the Import Invoice Macro• click the + icon when it appears in the watch• view every property imaginable for the object

The Object Browser

The object browser is the key tool to browse the Excel object library.

Access the Object Browser

• enter the VB Editor • press F2

Page 17: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

The top left drop down shows the libraries

Excel Libraries

• Excel • Office• stdole // used to embed objects from other apps in an Excel workbook

• VBA• VBAProject

Select the Excel library in the Object browser.

Now all the classes in the Excel library show in the left window. The textgets us to click on the Application class. The properties and methods for Application then show in the right window. Click ActiveCell. At the bottom we see ActiveCell is read-only, that is it cannot be assigned a value and returns a Range object .

Click Range (in the Classes column) and see it's properties and methods. (These can be thought to apply to Active Cell as well as one or more ofthe cells in a Range may be active.) Click a property and then the yellow question mark to get information on it.

Property, Method & Event Symbols

• green flying book → designate functions• index card with a hand pointing → properties• yellow lightning strikes → events // a later topic

The hyperlinks and search capabilities make the Object browser a more powerful tool for investigating the API (Application ProgrammingInterface) of Excel than just an alphabetically indexed reference manual.

What's a Property & What's an Object Confuses Object Browsing

As mentioned earlier, Excel is a little 'wiley' from an object-oriented point of view in thatproperties can be called on to return other objects. Many items such as Cells, Columns and Rows that you might have expected to be defined as classes in their own right are described as properties.

As stated earlier, it makes sense to think of VBA properties as objects in their own right.

Page 18: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

From a practical point of view, this can be all be ignored reasonably well, except when it comes to using the object browser it is a little confusing as you don't initially know whether to look for something under the class category or as a property of a class.

Aside from using the icons that symbolize what kind of element you are looking at, it seems you pretty much just have to discover as you go what is being called a propertyand what is being called an object.

Tips for Refining Recorded Code

The text offers the following tips to clean up recorded code.

1. Don't Select

With few exceptions, if programming a macro directly, the select action is not used. This is an artifact of using the recorder.

Highlight and cut the Select and the returned Selection and leave what the VBA Macro actually does.

Before Example // from 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad

Cells.Select Selection.Columns.Autofit

// goes to

After Example

Cells..Columns.Autofit // highlight Select.Selection & Delete

2. Use Cells( 1,1 ) Is Preferable to Range(“A1”)

This is covered in detail in the next chapter of the textbook.

3. To Find Last Row Start at the Bottom Up

Using End+Down doesn't always work as it takes you to the last row of the current range and not necessarily the last row with data in the worksheet. The better way, to go from bottom up, is shown below.

Example

Cells(Rows. Count, 1).End(xlUp)

Page 19: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

// Rows.Count is better than hard coding 'A65536' or 'A1048576' because// of potential version imcompatibilites See text note on page 60

4. Avoid Hard Coding Rows and Formulas; Use Variables

This is an extension of the detail described in italics above.

Example // from 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad

FinalRow =Class(Rows.Count, 1).End(xlUp).RowCells(FinalRow + 1, 1).Value = “Total” Cells(FinalRow + 1, 5).Formula = “=SUM(E2:E” & FinalRow & “)”

Another Rudiment

VBA uses the ampersand symbol, &, to concatenate String values.

Concatenation Example

Sub Cat() Range("$A$1").Value = "Con" & "cat" & "enate" & " This!" ' just to move the cursor Range("$G$1").Select End Sub

5. Use R1C1 Formulas To Make Life Simpler

R1C1 style, that uses row and column numbers has been largely replaced by use of A1 style which makes a more humanly readable number letter coordinate system. On occasion the double number system works better with some sorts of calculations. (Chapter 6 of the textbook shows us how to work with R1C1 formulas.)

The example in point supplied in the text shows us how three totalscan be executed using a resize.

Example // from 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad

Cells(FinalRow +1,5).Resize(1,3).FormulaR1C1 = “=SUM(R2C:R[-1]C”

// more on this later

Page 20: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

6. Converting a Copy Paste To a Single Statement

In record mode a range is often copied, over to another rangevia a call on ActiveSheet.Paste. The bloated code goes as follows.

Example // from 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad

Range('E14').SelectSelection.CopyRange(“F14:G14”).SelectActiveSheet.Paste

This code can be reduced to the following.

Example // from 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad

Range('E14').Copy Destination:=Range(“F14:G14”) // range is assigned to fx parameter

7. Use the With … End Block to Avoid Redundancy

Consider the following redundant code where a number of textformatting attributes are being added to text in a range.

Example // from 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad

Range(“A14:G14”).SelectSelection.Font.Bold = TrueSelection.Font.Size = 12Selection.Font.ColorIndex = 5 Selection.Font.Underline = xlUnderlineStyleDoubleAccounting

This can be reduced to the following using a With ...End Block.

Example // from 'VBA & Macros' Microsoft Excel 2010, Bill Jelen & Tracy Syrstad

With Range(“A14:G14”).Font .Bold = True .Size = 12 .ColorIndex = 5 .Underline = xlUnderlineStyleDoubleAccountingEnd With

In certain applications the savings can be substantial. With ---End is covered again later.

Page 21: Objects, Debugging & Programming Tipspkomisar/VBA/2_Excel_Objects.pdf · In proper 'OOP' Properties and Functions of a class are referred to as 'class members'. ... to the object-oriented

Assignment

Work through code generated in the Case Study on page 62 of the text book making the code more efficient and streamlined by applying the good practices discussed in points 1 to 7 at the end of this note.

Submit a screen shot both of the output and of the new code once you have confirmed it works identically to the original source macro.

Please provide short comments as you go in the code (using the single apostrophe ) noting when a good practice is being applied so the code can serve as a useful reminder of what can be done.