VBA Programming Series...02 - IT Skills

This blog is for IT lovers, accounts and finance executives who want to add value in their professional life.

test

Welcome to our blog. This blog is for IT lovers, Accounts/Finance Executives who wants to add value in their career path.

Search This Blog

Tuesday, 8 May 2018

VBA Programming Series...02

test

Inserting a bunch of text


If you often need to enter your company name, address, and phone number in your worksheets, you can create a macro to do the typing for you. You can extend this concept as far as you like. For example, you might develop a macro that automatically types a list of all salespeople who work for your company.


Automating a task you perform frequently


Assume you’re a sales manager and you need to prepare a month-end sales report to keep your boss happy. If the task is straightforward, you can develop a VBA program to do it for you. Your boss will be impressed by the consistently high quality of your reports, and you’ll be promoted to a new job for which you are highly unqualified.


Automating repetitive operations


If you need to perform the same action on, say, 12 different Excel workbooks, you can record a macro while you perform the task on the first workbook and then let the macro repeat your action on the other workbooks. The nice thing about this is that Excel never complains about being bored. Excel’s macro recorder is similar to recording live action on a video recorder. But it doesn’t require a camera, and the battery never needs to be recharged.


Creating a custom command


Do you often issue the same sequence of Excel menu commands? If so, save yourself a few seconds by developing a macro that combines these commands into a single custom command, which you can execute with a single keystroke or button click. You probably won’t save that much time, but you’ll probably be more accurate. And the guy in the next cubicle will be really impressed.


Creating a custom button


You can customize your Quick Access toolbar with your own buttons that execute the macros you write. Office workers tend to be very impressed by buttons that perform magic.

If you’re using Excel 2010, you can even add buttons to the Ribbon — something that’s off-limits in Excel 2007.


Developing new worksheet functions


Although Excel includes numerous built-in functions (such as SUM and AVERAGE), you can create custom worksheet functions that can greatly simplify your formulas. I guarantee you’ll be surprised by how easy this is.  Even better, the Insert Function dialog box displays your custom functions, making them appear built-in. Very snazzy stuff.

Creating complete, macro-driven applications


If you’re willing to spend some time, you can use VBA to create large-scale applications complete with a custom Ribbon tab, dialog boxes, on-screen help, and lots of other accoutrements. 


Creating custom add-ins for Excel


You’re probably familiar with some of the add-ins that ship with Excel. For example, the Analysis ToolPak is a popular add-in. You can use VBA to develop your own special-purpose add-ins. I developed my Power Utility Pak add-in by using only VBA, and people all around the world pay me real money so they can use it.


Advantages and Disadvantages of VBA


VBA advantages


You can automate almost anything you do in Excel. To do so, you write instructions that Excel carries out. Automating a task by using VBA offers several advantages:

✓ Excel always executes the task in exactly the same way. (In most cases, consistency is a good thing.)

✓ Excel performs the task much faster than you can do it manually.

✓ If you’re a good macro programmer, Excel always performs the task without errors (which probably can’t be said about you or me).

✓ If you set things up properly, someone who doesn’t know anything about Excel can perform the task.

✓ You can do things in Excel that are otherwise impossible — which can make you a very popular person around the office.

✓ For long, time-consuming tasks, you don’t have to sit in front of your computer and get bored. Excel does the work, while you hang out at the water cooler.

VBA disadvantages


It’s only fair that I give equal time to listing the disadvantages (or potential disadvantages) of VBA:

✓ You have to know how to write programs in VBA. Fortunately, it’s not as difficult as you might expect.

✓ Other people who need to use your VBA programs must have their own copies of Excel. It would be nice if you could press a button that transforms your Excel/VBA application into a stand-alone program, but that isn’t possible (and probably never will be).

✓ Sometimes, things go wrong. In other words, you can’t blindly assume that your VBA program will always work correctly under all circumstances. Welcome to the world of debugging and, if others are using your macros, technical support.

✓ VBA is a moving target. As you know, Microsoft is continually upgrading Excel. Even though Microsoft puts great effort into compatibility between versions, you may discover that VBA code you’ve written doesn’t work properly with older versions or with a future version of Excel.

VBA in a Nutshell


Just to let you know what you’re in for, I’ve prepared a quick and dirty summary of what VBA is all about. 

✓ You perform actions in VBA by writing (or recording) code in a VBA module. You view and edit VBA modules by using the Visual Basic Editor (VBE).

✓ A VBA module consists of Sub procedures. A Sub procedure has nothing to do with underwater vessels or tasty sandwiches. Rather, it’s a chunk of computer code that performs some action on or with objects (discussed in a moment). The following example shows a simple Sub procedure called AddEmUp. This amazing program displays the result of 1 plus 1.


Sub AddEmUp()
Sum = 1 + 1
MsgBox “The answer is “ & Sum
End Sub

A Sub procedure that doesn’t perform properly is said to be substandard.

✓ A VBA module can also have Function procedures. A Function procedure returns a single value. You can call it from another VBA procedure or even use it as a function in a worksheet formula. An example of a Function procedure (named AddTwo) follows. This Function accepts two numbers (called arguments) and returns the sum of those values.


Function AddTwo(arg1, arg2)
AddTwo = arg1 + arg2
End Function

A Function procedure that doesn’t work correctly is said to be dysfunctional.

✓ VBA manipulates objects. Excel provides dozens and dozens of objects that you can manipulate. Examples of objects include a workbook, a worksheet, a cell range, a chart, and a shape. You have many more objects at your disposal, and you can manipulate them by using VBA code.

✓ Objects are arranged in a hierarchy. Objects can act as containers for other objects. At the top of the object hierarchy is Excel. Excel itself is an object called Application. The Application object contains other objects such as Workbook objects and Add-In objects. The Workbook object can contain other objects, such as Worksheet objects and Chart objects. A Worksheet object can contain objects such as Range objects and PivotTable objects. The term object model refers to the arrangement of these objects. 


✓ Objects of the same type form a collection. For example, the Worksheets collection consists of all the worksheets in a particular workbook. The Charts collection consists of all Chart objects in a workbook. Collections are themselves objects.

✓ You refer to an object by specifying its position in the object hierarchy, using a dot (that is, a period) as a separator. For example, you can refer to the workbook Book1.xlsx as


Application.Workbooks(“Book1.xlsx”)

This refers to the workbook Book1.xlsx in the Workbooks collection. The Workbooks collection is contained in the Application object (that is, Excel). Extending this to another level, you can refer to Sheet1 in Book1. xlsx as


Application.Workbooks(“Book1.xlsx”). _
Worksheets(“Sheet1”)

As shown in the following example, you can take this to still another level and refer to a specific cell (in this case, cell A1):


Application.Workbooks(“Book1.xlsx”).
Worksheets(“Sheet1”).Range(“A1”)

✓ If you omit specific references, Excel uses the active objects. If Book1. xlsx is the active workbook, you can simplify the preceding reference as follows:


Worksheets(“Sheet1”).Range(“A1”)

If you know that Sheet1 is the active sheet, you can simplify the reference even more:


Range(“A1”)

✓ Objects have properties. You can think of a property as a setting for an object. For example, a Range object has such properties as Value and Address. A Chart object has such properties as HasTitle and Type. You can use VBA to determine object properties and also to change properties.

✓ You refer to a property of an object by combining the object name with the property name, separated by a dot. For example, you can refer to the Value property in cell A1 on Sheet1 as follows:


Worksheets(“Sheet1”).Range(“A1”).Value


✓ You can assign values to variables. A variable is a named element that stores information. You can use variables in your VBA code to store such things as values, text, or property settings. To assign the value in cell A1 on Sheet1 to a variable called Interest, use the following VBA statement:


Interest = Worksheets(“Sheet1”).Range(“A1”).Value

✓ Objects have methods. A method is an action Excel performs with an object. For example, one of the methods for a Range object is ClearContents. This aptly named method clears the contents of the range.

✓ You specify a method by combining the object with the method, separated by a dot. For example, the following statement clears the contents of cell A1:


Worksheets(“Sheet1”).Range(“A1”).ClearContents

✓ VBA includes all the constructs of modern programming languages, including arrays and looping. In other words, if you’re willing to spend a little time mastering the ropes, you can write code that does some incredible things.

Believe it or not, the preceding list pretty much describes VBA in a nutshell. Now you just have to find out the details. 

An Excursion into Versions


If you plan to develop VBA macros, you should have some understanding of Excel’s history. I know you weren’t expecting a history lesson when you picked up this book, but bear with me. This is important stuff that might make you a hit at the next nerd party.

Here are all the major Excel for Windows versions that have seen the light of day, along with a few words about how they handle macros:

✓ Excel 2: The original version of Excel for Windows was called Version 2 (rather than 1) so that it would correspond to the Macintosh version. Excel 2 first appeared in 1987, but nobody uses it anymore, so you can pretty much forget that it ever existed.

✓ Excel 3: Released in late 1990, this version features the XLM macro language. Nobody uses this version either.


✓ Excel 4: This version hit the streets in early 1992. It also uses the XLM macro language. A small number of people still use this version. (They subscribe to the philosophy if it ain’t broke, don’t fix it.)

✓ Excel 5: This one came out in early 1994. It was the first version to use VBA (but it also supports XLM). Excel 5 users are becoming increasingly rare.

✓ Excel 95: Technically known as Excel 7 (there is no Excel 6), this version began shipping in the summer of 1995. It’s a 32-bit version and requires Windows 95 or Windows NT. It has a few VBA enhancements, and it supports the XLM language.

✓ Excel 97: This version (also known as Excel 8) was born in January, 1997. It has many enhancements and it features an entirely new interface for programming VBA macros. Excel 97 also uses a new file format (which previous Excel versions cannot open). Occasionally, I run into someone who still uses this version.

✓ Excel 2000: This version’s numbering scheme jumped to four digits. Excel 2000 (also known as Excel 9) made its public debut in June 1999. It includes only a few enhancements from a programmer’s perspective, with most enhancements being for users — particularly online users. With Excel 2000 came the option to digitally sign macros, thus enabling you to guarantee that the code delivered to your users is truly yours. Excel 2000 still has a modest number of users.

✓ Excel 2002: This version (also known as Excel 10 or Excel XP) appeared in late 2001. Perhaps this version’s most significant feature is the ability to recover your work when Excel crashes. This is also the first version to use copy protection (known as product activation).

✓ Excel 2003: Of all the Excel upgrades I’ve ever seen (and I’ve seen them all), Excel 2003 has the fewest new features. In other words, most hardcore Excel users (including yours truly) were very disappointed with Excel 2003. Yet people still bought it. I think these were the folks moving up from a pre-Excel 2002 version. As I write this, Excel 2003 is probably the most commonly used version.

✓ Excel 2007: Excel 2007 signaled the beginning of a new era. Excel 2007 dumped the old menu and toolbar interface and introduced the Ribbon. It also allows much larger worksheets — more than a million rows.

✓ Excel 2010: The latest, and without a doubt, the greatest. Microsoft outdid its corporate self with this version. This version has some slick new features (such as sparkline graphics), and it also performs quite a bit better in some areas. And if you need really, really huge workbooks, you can install the 64-bit version.


This is written for Excel 2007 and Excel 2010, so if you don’t have one of those versions, you run the risk of getting confused in a few places.

So what’s the point of this mini history lesson? If you plan to distribute your Excel/VBA files to other users, it’s vitally important that you understand which version of Excel they use. People using an older version won’t be able to take advantage of features introduced in later versions. For example, if you write VBA code that references cell XFD1048576 (the last cell in a workbook), those who use a version prior to Excel 2007 will get an error because those pre-Excel 2007 worksheets only had 65,536 rows and 255 columns (the last cell is IV65536).

Excel 2007 and Excel 2010 also have some new objects, methods, and properties. If you use these in your code, users with an older version of Excel will get an error when they run your macro — and you’ll get the blame. However, Microsoft has made available an Office Compatibility Pack, which allows users of Excel 2003 and Excel XP to open and save workbooks in the new file format. This product (which is free, by the way) doesn’t give these older versions the new features. It just lets them open and save files in the Excel 2007/2010 file format.

No comments:

Post a Comment

Popular

Welcome to our blog. If you want to; learn writing skills, preparation for CSS/Corporate laws, IT skills, downloading Business/IT books, and many more; this blog is for you.