excel 2010 introduction to vba - my online training...
TRANSCRIPT
Excel 2010 Introduction to VBA Visual Basic for Applications
Chris “Smitty” Smith MrExcel.com
3/4/2016
Excel 2010 - Introduction to VBA Programming 1
Introduction egardless of what department you’re in, whether it’s Finance, Accounting, Sales,
Operations, Marketing, etc., if you use Excel with any regularity then there are
innumerable activities that require some degree of repetition on your part. It can be
as simple as formatting a weekly report, pulling information from some internal corporate
data warehouse, reviewing and consolidating workbooks from other departments, you
name it. Whatever the task(s) may be, the repetitive, mundane stuff is without a doubt the
part of dealing with Excel that most people find to be the least enjoyable. Wouldn’t it be
nice if there was a way reduce or even eliminate some of that repetitive work? Most
people would find all kinds of productive ways to re-apply that time saved if they could.
Fortunately, there is a way you can automate a good part of your regular work with Excel,
and it’s right at your fingertips. It’s called Visual Basic for Applications (VBA for short), and
it can make your life a lot easier. In fact, you should be able to walk away from this course
with the ability to streamline at least several of your most time consuming tasks. If you’re
not familiar with VBA, why haven’t you heard of it up until now? For whatever reason,
Microsoft doesn’t do a good job of publicizing VBA within the Office community, although
most everyone who programs with a Microsoft technology and deals with Office
applications knows about it. You would think that Microsoft would want everyone to know
about such a time-saving tool wouldn’t you?
What is VBA? xcel (and most other Office products) comes bundled with Visual Basic for
Applications (VBA), but what is it? VBA is a subset of the powerful Visual Studio.NET
programming language that Microsoft uses to create Office applications, and they
allow Office users to access/harness some of that power through VBA. Most other product
providers don’t let you do that, which is one of the reasons why Excel is so much more
powerful than other spreadsheet applications. For instance, Microsoft’s new web app
version of Excel doesn’t support VBA; Google Spreadsheets have no internal programming
capability either, so you can’t automate any tasks with either one of those, while Lotus 1-2-
3 only gives you the ability to record keystrokes. In that sense you have more automation
ability with Lotus than the Excel web version or Google, but it is strictly limited to what you
can do within the Lotus interface itself; you can’t get behind the scenes like you can with
Excel, and it can make a huge difference to your daily work. Does that mean that the Excel
Web App, Google Spreadsheets or Lotus 1-2-3 aren’t useful programs? Of course not, they
just lack the intrinsic programmability that Excel has, but certainly each has its place. This is
especially true with online collaboration, which the Excel Web App allows you to do.
Before we take a single step further you should understand that first and foremost, if you’re
not a computer programmer, don’t worry! You don’t need to become one in order to start
taking advantage of VBA. In fact, you never even have to go behind the scenes with VBA in
order to start using it (although once you get the hang of it you might find yourself more
interested in it than you are scared of it). Is trepidation a perfectly natural emotional
response? Absolutely! You’re about to embark on a side of the Office environment that
most people don’t get a chance to see.
R
E
VBA Case Study
A Senior Financial Analyst in
the Finance Department at a
Fortune 100 organization
spent 3-4 days each month
creating corporate Month-
End Analysis Reports.
Through the use of VBA that
process was cut to less than
2 minutes!
Excel 2010 - Introduction to VBA Programming 2
What can you do with VBA? ame it…In short, just about any repetitive, predictable task in Excel can be automated with VBA. Automated tasks can
range from the relatively mundane like simple report formatting, to complex processes that speak to other applications and
transfer data between them and Excel. One of the most immediate benefits of using VBA is that your computer’s processor
can do things exponentially faster than you can, so even if you were to make no enhancements to a process, but simply have Excel
repeat it for you, you’ll end up saving substantial amounts of time. In general, even the most complex VBA code that someone has
written pays for its investment of time far faster than if you were to continue repeating the manual process. Once you automate
your first process you’ll probably find yourself coming back for more. If you can think of a way to automate a process or procedure,
then odds are it can be accomplished in VBA. And you don’t have to limit yourself to VBA in Excel; many of the general VBA
concepts we discuss in this course will readily translate to other Office applications.
The Developer Tab he first thing we need to do is expose VBA functionality in Excel. Remember
that Microsoft doesn’t do a great job promoting VBA? Well they do such a
good job of that, they actually hide it from you as Excel’s default setting, so
we need to go unhide it. Goto FileOptionsCustomize the Ribbon and in the
Main Tabs section on the right, check the box next to “Developer”. When you
return to Excel you’ll see the Developer tab on the very right of the Ribbon groups.
The first thing we need to do since this is a relatively new interface for most people
is to review the elements of the Developer tab.
If you’re already somewhat familiar with the new Ribbon interface, then this
shouldn’t be too much of a surprise to you, as it’s laid out just like any of the other
Ribbon groups. In fact, the Developer tab is probably the most straightforward of
the Ribbon tabs. There are 5 primary groups on the Ribbon, but for our purposes in
this course we’re only going to focus on 1 & 3, the Code and Controls tabs (although
you’ll get an overview of each).
N
T
Just a few things you can do with VBA
Create Monthly Reports (automatically)
Automate time consuming procedures
Create mass e-mails
Create dynamic charts & Dashboards
Add buttons to make it easy for end-users to navigate your workbooks
Automatically retrieve information from websites and corporate databases
Automate complex Budget & Forecasting processes
Manage Mail Merges with Word
Create custom Menus and Add-Ins specific to your business
Create your own custom functions (great for Scientists)
Monitor user changes in Workbooks and Worksheets and respond to them
Add buttons to make it easy
Excel 2010 - Introduction to VBA Programming 3
Code – This group is where you’ll spend most of your time when it comes to
recording and calling macros.
o Visual Basic – this will open the Visual Basic Editor (VBE), which is the
actual VBA interface. We’ll get to that part later, so don’t worry about
it for now.
o Macros – This will display a list of all Macros in open workbooks. Oddly
enough, this will load the Excel 2003 Macro Dialog. If you’ve used Excel 2007
or 2010 at all you probably recognize by now that when you call deeper
functionality from the Ribbon you’re generally exposing Excel 2003 dialogs.
Future versions of Excel will probably see these revamped to match the look
and feel of the Ribbon.
o Record Macro – This is your gateway to the Macro Recorder, which we’ll get
to shortly. If you’ve never dealt with a programming language before (and
think you’ll need to be dragged to one kicking and screaming), then this is
where you can relax and let VBA do all the work for you without you lifting a
finger as a programmer. Unfortunately, we needed to get a lot of
housekeeping issues and introductions out of the way before can get to the
fun stuff, but we’re almost there, so just hang on a little bit longer.
o Use Relative References – We’ll get to this one later, but if you’re familiar with R1C1 formula style vs. Cell Address
Style (A1:B1), then this one will make sense to you. It’s just a way of telling VBA which style to record in.
Why the Ribbon?
In 2007 Microsoft completely revamped the look of the primary Office applications when it introduced
what is called the Fluent User Interface (more commonly referred to as the %$#*@ Ribbon). This was an
attempt to introduce a more cohesive end-user environment to Office applications, and while it was
reviled by most experienced Office users, it has proven to be a big hit with newer users. In addition, as
Office products have evolved, so have the number of commands available to users (there are hundreds!), so
Microsoft had to develop a way to easily expose all of those options graphically, instead of hiding them in
more and more layers that the user had to know.
Figure 1 - The Developer Tab
Excel 2010 - Introduction to VBA Programming 4
o Macro Security – This is one that you’ll need to address, otherwise VBA stands a good chance of being stopped dead in
its tracks. We should probably take care of this one now, so go ahead and click it. Once you do you’ll see the following
dialog.
If (and this is a deal-breaker), only if you have a corporate level Virus Scan application, then as counter-intuitive as
this might sound, go ahead and check the last option button – Enable all macros (yes, the one that says “not
recommended). And also check the box that says “Trust access to the VBA project object model”. Why shouldn’t
you worry about this? Because any malicious code that tries to come in via an Excel workbook is going to get
stopped by the Virus Scan program before you ever get the chance to open it.
Add-Ins – These are tools that expose greater functionality in Excel than it ships with natively.
Some are written by Microsoft, while scores more are written by third-parties. If you do a lot of
financial analysis work you might be interested in the Analysis ToolPak, which is a Microsoft Add-In
that exposes more analytical functions than you normally have. Similarly, there are Statistical Add-
Ins, and now there is Microsoft’s amazing PowerPivot Add-In, which will turn data analysis on its
ear! You can also access Add-Ins from the FileOptionsAdd-Ins menu.
Controls – This is where you give life to end-user applications. The primary element
you’ll want to pay attention to on the Controls group is the Insert menu, which exposes
Forms controls, which don’t require VBA, as well as ActiveX controls that do. This
course isn’t going to cover how to use Forms controls in depth, but if you do any work
at all with creating Forms in Excel, then this is a toolbar with which you should become
familiar, as it can make filling in forms much easier for your end-users. However, you
should know that you can assign your recorded macros to Forms Buttons (and Drawing
Shape objects), both of which we will be discussing later in the course.
Why shouldn’t you worry about Macro Security in Office applications?
Because it’s a Zero-Sum game. Why bother writing malicious code for those relatively few people who are
passing Office documents back and forth (even less so outside of corporate confines), when literally everyone
has access to the Internet and e-mail? It makes much more sense to target the masses. That’s why you
don’t see a lot of malicious code targeted toward the MAC platform.
Excel 2010 - Introduction to VBA Programming 5
Form Controls consist of the following objects*, many of which you’ll be familiar with in today’s digital environment.
Button
ComboBox
Check Box
Spin Control
List Box
Option Buttons (aka Radio Buttons)
Frame Control (for grouping Option Buttons)
Label (for Text)
ScrollBar
The last three objects, Text Box, ComboList, and Combo Drop-Down are legacy controls that are no longer
supported (so why are they there? Good question…).
ActiveX Controls – These are very similar to Forms controls except that they are controlled by VBA and you actually
need to program against them in order to get them to work. Think of the two sets of controls this way: Recorded
Macros are to Forms controls as hand written VBA code is to ActiveX controls.
XML – In all likelihood you’ll never run into this unless you’re dealing with
corporate documents and posting them on the Internet. It’s relatively
complicated, and probably not all that useful in any aspect of your normal
business activities. Why is it on the Developer tab? Because it’s one of those
things that’s best left hidden from everyone, except those few who specialize in
it. In fact, XML probably shouldn’t be something that’s exposed natively, but
held in captivity as an Add-In for those who might actually use it.
Modify – This has about the same relevance for Excel users as XML. Even the most seasoned VBA
programmers will never even touch the backside of this one, so don’t even worry about it.
* What’s an Object anyway?
VBA and its parent, Visual Basic, are what are called Object Oriented Programs. This means that almost
every part of an application is considered an object, and you can program against it (meaning you can
identify it and work with it). In Excel a Cell is an object, as are worksheets, workbooks, charts, controls,
graphics, etc. A good way to understand it is to insert a graphic on a worksheet, grab it with the mouse
and move it around. There, you just moved a physical “object” – In computer terms anyway. If you can
think of objects in abstract terms it will be easier, because it’s not really like picking up a ‘real” object from
your desk is it?
Excel 2010 - Introduction to VBA Programming 6
First Steps…The Macro Recorder ow that all of the boring stuff’s out of the way we’re going to talk about the Macro Recorder. But wait a minute, we were
talking about VBA and all of these confusing tools and elements, and now we’re talking about the “Macro Recorder”?
What’s that? The Macro Recorder is a tool that Microsoft has included in many Office applications, and it is one that you
will come to rely on for automating your work in Office. So what does it do? In Excel’s case, the Macro Recorder essentially records
almost every step/action you take in an Excel workbook, from when you turn it on until you turn it off. For many people who just
need to speed up a manual process, this is all they never need to do. In fact, if a recorded macro does what it needs to do, then you
never need to go past that. Just record a macro, make sure it does what you want, and call it over and over again. Really, that’s all
there is to it? Really, that’s it. This is your interaction with VBA at its lowest level, and it never needs to be any more complicated
than flipping a switch, doing something and then turning it off. In fact, it’s so easy that many people who record macros and use
them every day never even realize that they are intrinsically working with VBA.
Some people may argue that it’s best to jump right in with both feet and fully immerse you in VBA, the concepts behind the Object
Oriented programming language, and inundating you with terminology and esoteric concepts, instead of taking a step back and
understanding that many people will never need to know those things. So we’re going to start in the logical place, which is where
most people would start if they were to try to tackle VBA on their own. Some of you will never go past this stage, and that’s just
fine, while others will choose to explore VBA further, which is fine as well. The most important thing is that you walk away from this
course with a basic understanding of how to start automating your daily Excel work. How far you decide to take that is entirely up to
you.
N
Basic Rules of Thumb to consider before even tackling the Macro Recorder
1. Always work on a backup copy of your original workbook (just as you should before making any major
changes to a workbook). This goes directly to the mantra: "Save Early, Save Often", that should apply
to all digital work.
2. You cannot screw up a workbook or worksheet by recording a macro (other than what you screw up
while recording it). But if you're working on a backup copy it really doesn't matter.
3. See Rule #1 - Always work on a COPY of your workbook before you record a macro, and especially
before you run a recorded macro.
4. If you run a Macro, recorded or not, it cannot be undone. (Actually it can, but it takes more
programming in advance anticipation of having to undo something that it's just not worth it). Again, if
you are working on a backup copy of your workbook it doesn't matter.
5. At some point in time you will ignore those rules and lose some work. Get used to it, it happens.
6. Buy donuts for the IT folks – They’re the ones who will hopefully recover your work. (You should be nice
to them anyway, since they keep your computers working, so you can make your boss look good).
Excel 2010 - Introduction to VBA Programming 7
How does the Macro Recorder Work? he Macro Recorder is a literal recorder, in that it records everything that you do. It’s not necessarily the most efficient tool in
terms of overall performance, but what’s important is that it gets the job done. Will you run into things that the Recorder just
can’t handle? Sure. As you’re starting out you’ll be hard pressed to stump it though. So let’s dig in and get going on it!
First, just to get used to things, open a new Excel workbook, go to the Developer Tab on the Ribbon and press the Record Macro
button (alternatively you can use keystrokes ALT+T+M+R). As soon as you’ve done that you’ll see an Excel 2003 Record Macro
dialog.
You have a few very simple options in the Record Macro dialog, and for now we’re going to
ignore them and just get going, so just hit OK. Now start doing anything on the worksheet,
select some cells and format them, add some text and format it, etc. Yes, that’s it. While you’re
doing your thing the Macro Recorder is also doing its thing and it’s capturing everything you’re
doing. When you’re done you can go back to the Developer tab and click the Stop Recording
button (as soon as you start recording a macro the “Record Macro” option changes to “Stop
Recording” - you can also use the keyboard shortcut ALT+L+R).
Now select any other worksheet and go back to the Developer tab, select Macros and choose
Macro1 from the list, then Run. Every action you stepped through on the first worksheet is
automatically recreated on the second, and almost instantly!
Here’s a very simple example:
And here are the sequential steps it took to do that:
OK, so that took four whole steps. Nothing ground breaking or Earth shattering is it? But imagine having to do this hundreds, if not
thousands of times over the course of a year. The effort adds up. How much time did it take you to record your manual steps for
your first encounter with the Macro Recorder (stalling time because it was something new notwithstanding)? A minute or two?
How long did it take your recorded macro to do it for you? Those simple four steps shown above ran in much less than a second, in
fact probably a millisecond. The Macro Recorder’s not so scary after all is it?
About now, you’re probably starting to think that this whole VBA thing might have some potential aren’t you?
T
Excel 2010 - Introduction to VBA Programming 8
A General Note on the Macro Recorder he Macro Recorder is your friend. In fact, it’s such a great tool, that even seasoned VBA programmers use it to develop code. Why? Because the recorder will also generate complex syntactical statements that a programmer might not necessarily get right. Case in point: let’s say you need to open an Excel workbook that’s sitting on a server somewhere. That’s not so hard, you just navigate to it right? Now try telling VBA to do that by actually writing the code by hand. Sure, you could try, but
why, when the recorder can do it for you:
Workbooks.Open Filename:= _ "F:\\NetNeo00\LocalHost\SvhSrv\MOSS\%SharedFiles\LocalUser\Documents\FP&A\071511 - FP&A Data.xlsx"
Which would you rather do, write that by hand or let the Recorder do it for you? What are the odds that somewhere in that file path you’re going to spell something wrong? Here’s where things like this become very important: VBA is very picky about what you tell it to do, and something as seemingly insignificant as a leading or trailing space in a file name can cause your code to fail. Debugging code is something that every programmer needs to do, but if you can avoid potentially building errors in your code by using the tools that you have at hand, then by all means use them! Another consideration is that even if you type 90+ WPM, the recorder can write code a lot faster than you can.
But (and there’s always a “but” isn’t there?), the Macro Recorder is just that: a Recorder. And it is a literal recorder, so it records literally everything that you do. If you make a mistake and undo it, that action will be recorded and repeated when you run the macro. If you open a workbook to copy something from it, but open the wrong one by mistake, it’s going to get opened when you run the macro. The recorder will also record all of your screen navigation, like moving from sheet to sheet or even scrolling up, down, across, etc., so while it’s a great tool, it can also be pretty inefficient; worksheet and workbook navigation have absolutely no bearing on what your code does, but the recorder isn’t smart enough to exclude it. The other thing is that when you run your recorded code all of that navigation will be replayed and you’re going to see it all happen. That means your end users will see it too (although there are ways to eliminate that, which we’ll discuss a bit later). That’s why you’re encouraged to record a macro performing a task with which you’re intimately familiar. The more smoothly you can execute a procedure while recording a macro, the more efficient it’s going to be when it’s played back. Later in the lesson we’ll be reviewing some recorded code, dissecting it, and showing you what makes it tick, and which parts you do and don’t need.
T
Independent Study
Your next task is to go off on your own and record a macro in one of your own workbooks. Why one of your own?
Because this whole recording macro thing will make more sense if you can tie it to a process with which you’re
intimately familiar, as opposed to a random exercise. So open one of your own Excel workbooks, preferably one in
which you do a lot of repetitive stuff (it can be copying and pasting from another workbook, formatting a report,
anything). The key is to pick a task with which you are so intimately familiar you can essentially repeat it by rote.
Put it this way, you want to pick something that you’ve got down cold and could do in your sleep. Now make a
copy of it. Once you’ve made a copy of the workbook, make a copy of the worksheet that you’re going to be working
with (you can make a quick copy by right-clicking the worksheet tab, select Move or Copy, check the “Create a
copy” button and hit OK). Once you’ve done that, go to the Developer tab and click the Record Macro button. You
can add a name to the macro if you like, or just leave it as the default “Macrox” that Excel gives you. Then go
ahead and start doing what you would normally do. When you’re done, press the Stop Recording button. Now
insert a blank worksheet (ALT+I+W), save the workbook and select your macro from the Macros dialog on the
Developer tab and run it. If everything runs as it should then you just gained some insight into how recorded
macros can start helping to streamline some of your processes. Pretty cool, huh?
Excel 2010 - Introduction to VBA Programming 9
The Macro Recorder – In Depth ow that you’ve had a chance to do a bit of work with the Macro Recorder,
we’re going to break it down and show you what each part of it does,
from when you first start recording a new macro, to when you come back
to play one.
Macro Name – This is the first part of the Record Macro dialog. In our
examples we just stuck with VBA’s default “Macrox” name assignment,
because it really didn’t matter. When you start recording your own macros for
work you’ll want to give them descriptive names, so that you know which one
to choose from a list of perhaps 10-20 or more.
Shortcut Key – You can assign keyboard shortcuts to your macros! You don’t need to
select the macro you want to run from the list of macros, which is incredibly convenient,
especially if you have some boilerplate code that you run all the time. An example would be
code that adds a particular format for a header row and autofits columns. You could
potentially call that several times during your interaction with a workbook, so a keyboard
shortcut is much more efficient than selecting from a list.
Store Macro In – In most cases you’ll store your macro in the same workbook in which
you’re recording. But what if you want to use that macro globally and not just on that
workbook? You could copy the code into each workbook, but that’s not very efficient,
especially if you ever need to change it. Fortunately, there’s a great hidden workbook
called “Personal.xls”. Think of it as your personal macro library. Any code you record in
the Personal Macro Workbook
will be available to any open
workbook in any instance of
Excel. Just select it from the
“Store macro in:” drop-down before you start recording.
Macro Description – Adding a description to your macro is always a good idea. It’s good practice for anyone down the line
who might have to run your macro, and it’s also good for you. It’s not at all uncommon to revisit some code a year after it was
N
WARNING!
You can assign existing Office/Excel keyboard shortcuts to your macros; nothing is going to stop you from assigning Ctrl+C
(Copy) to your code. What’s going to happen if you do that? Right, Ctrl+C no longer copies, it runs your code instead. You
need to be very careful when selecting keyboard shortcuts to not select one that Excel is already using. Fortunately, you can
add Shift to the mix, which is highly recommended, since there’s far less crossover between existing commands. When you
add Shift you’ll see it in the Macro dialog. It’s as simple as holding down the Shift key when you enter your shortcut letter
(it can’t be a number or non-alpha character).
Figure 2 - Personal Macro library
Excel 2010 - Introduction to VBA Programming 10
written to make some adjustments to it. Without comments you might spend a good deal of time just trying to figure out what
the code does before you can even start making changes.
Working with Stored Macros Now we’re going to discuss your options after you’ve recorded a macro. Click the Macro button on the Developer tab (alternately you can use ALT+T+M+M). That will launch the Macro dialog (this is another Excel 2003 dialog). You have six options:
Run – This will run the selected Macro. If you have several macros to choose from,
make sure that you select the right one, because if you inadvertently run the wrong
macro on the wrong workbook there’s no undoing it unless you close the workbook
without saving it. This is where descriptive macro names are very useful.
Step Into – This is for more advanced use and allows you to actually step into the
code within the VBA environment for testing and debugging. Go ahead and try it if
you’re interested (ALT+Q will exit the VB Editor and take you back to Excel). If you
choose this option, the F5 key will execute your code immediately and F8 will let you run it one line at a time. To cancel it you
can goto RunReset (ALT+R+R).
Edit – This opens the VBE as well, but your code hasn’t been initiated.
Create – This will generally never become enabled, so don’t worry about it. It’s
quite possibly a legacy control that someone at Microsoft forgot to take out.
Delete – Does what it says, so be careful. There’s no Recycle Bin from which to
retrieve a deleted macro.
Options – This just exposes the Shortcut Key option and the Macro Description pane.
Macros In – You can choose which open workbook you want to view. This can be useful if you have a few workbooks open and
they all have macros. Sometimes you just don’t want to see the entire list, but just the ones specific to the workbook you’re in
at the time.
Commenting Code – It’s a good habit to start!
Commenting your code is very good practice. When you record macros all you have is the Macro Description,
but when you start interacting with VBA code and actually manipulating it yourself, comments are an
invaluable tool to both you and future developers. It can be a simple roadmap that outlines a procedure, or
very detailed description of what each individual process is doing. As we progress in the lesson you’ll see
examples of good and not so good comments.
Excel 2010 - Introduction to VBA Programming 11
Adding a Macro to the QAT (Quick Action Toolbar) – So far you’ve seen how to run
macros from the Macro dialog, and by adding keyboard shortcuts. You can also add your
macros to the Quick Action Toolbar, which is the mini-toolbar that sits above the Ribbon.
First click the button to modify the QAT (it’s the inverted pointer on the far right) and select the “More Commands” option.
Once the Customize dialog is launched, select the “Choose commands from:” option, select “Macros”, then find your macro in
the list and Add it.
Unfortunately, that’s not the nicest button image, so the first thing you’re going to do is change it by selecting the “Modify”
button, which will load a dialog full of button images. Select the image you want, and add a Display name (that will show up as
a Tool Tip if you hover over the button). Click OKOK and your new macro button will be on the QAT.
Other Ways to Run Macros hat if your macro works so well that you want to make it available to other users? Let’s say that you created a macro that formats a report that your entire department uses. People enter data into their report and then they have to manually format it, which takes time, so you know that your macro can help. How do you get people to use it? Do you really expect them to learn everything about macros that you have? Are you going to tell them to unhide the Developer
tab, and how to choose a macro from the list? Or do you think they’ll learn your keyboard shortcut? Not likely. And if the goal is to make life easier for users, then asking them to learn a bunch of stuff just to use your “automated” process is relatively counter-intuitive isn’t it? And you’re not going to go add a custom Macro button to each user’s QAT. Fortunately, there are some easy ways to bring your macros to your users in a way that’s almost entirely seamless to them.
W
Figure 3 - Add a Macro to the QAT
Excel 2010 - Introduction to VBA Programming 12
Forms Buttons – These are probably the most common controls used
to run macros. Goto the Developer tab and select a button control from
the Forms controls dialog in the Insert menu (the Button is the one on
the top left). Then draw a button on your worksheet, by dragging the
left-click button on the mouse – it can be any size you want. As soon as
you release the mouse you’ll see a new dialog. Select your macro from
the list and voila! When you click the button the macro will run. You
can change the button text by right-clicking it. You also have the option
of changing the font and size, but that’s it. Unfortunately, Forms
controls aren’t very robust, and they’re just kind of boring.
ActiveX Buttons – These are much more robust, but they also have to be coded directly in VBA. We’ll be discussing these
controls in the VBA section.
Shapes & Drawing Objects – This is where things can start getting kind of fun. Just as you assigned a macro to a button, you
can do the same thing with shapes, drawing objects, even graphics. Just right-click on them and select “Assign Macro”, and
choose your macro just like you did with the Forms Button. A common thing to do is assign a macro to a company logo, for
instance you can have a macro that automatically e-mails a workbook to a group of people. Just tell your users that they click
the company logo when they’re ready to go. Since Microsoft stepped up their game with new drawing objects in Office 2007,
using drawing objects has added a new dimension of flair to running macros; you can certainly make them much more engaging
than boring old buttons. One nice thing about both Forms buttons and using shapes for assigned macros is that you can copy
them from sheet to sheet and they’ll retain the assigned macro. This is great if you want to be able to reuse code on different
sheets.
Recorded Macros - Summary ow you know all you need to know to start recording your own macros and begin automating some of what you do every day. Bear in mind that as mentioned earlier the recorder is just that and nothing more. Once you get the hang of recording some macros, you’ll start to wonder if you can do other things that the recorder just can’t capture. The good news is that you can with some practice. The best thing you can do if you want to continue past what the recorder does is to start
understanding the VBA code itself. Anytime you want you can select Edit from the Macros List and take a look at the code. Let’s say you record a macro that applies some formatting; when you look at the code you should be able to see what the code is doing, based on the steps you took when recording it. It’ll look a lot like Greek at first, but you’ll get the hang of it pretty qu ickly. That’s another reason for recording procedures with which you’re familiar. It’s a lot easier to decipher the code if you already have an idea
N
E-Mail Report Next Page Error
Check Leave a
comment
Figure 4 - Drawing Objects with Assigned Macros
Excel 2010 - Introduction to VBA Programming 13
what it’s doing. From here on out we’ll be talking about VBA, so if you choose to go no farther, then good luck, and most of all have fun!
Visual Basic for Applications ow we’ll take a step beyond the Macro Recorder and start delving into VBA. The first thing that needs to be explained is the difference between a macro and VBA code. Macros are generally written by the Macro Recorder. They perform certain explicit tasks that can be repeated. The tasks are unwavering and do exactly what was recorded. There is no room for interpretation, so macros are generally not dynamic. VBA code on the other hand is deterministic, where actions are often
predicated by differing conditions, events and even user input. VBA is not intelligent per se, but it can be programmed to take certain conditions into account; however you, the programmer, are the one who tells VBA what those parameters might be. For instance, you can have VBA protect a worksheet for some users and unprotect it for others. You tell VBA who the users are, and it in turn evaluates each one and applies the rules that you have set for it.
But there’s still a lingering question: does this mean that I have to be a computer programmer to use VBA? Perhaps to its fullest extent you might, but a lot of times you’ll be interacting with VBA solely to make recorded code more efficient. You don’t necessarily need to know how to write VBA code in order to accomplish a great deal, but you do need to be familiar with the VBA Object Model. As mentioned in the beginning of the lesson, VBA is an Object Oriented Programming language (OOP). This concept essentially states that every part of an application is an object. A Workbook is an object, as is a Worksheet and a cell. A Chart is an object, as are controls, like Buttons, Combo Boxes, etc.
N
Excel 2010 - Introduction to VBA Programming 14
Unit Summary: Introduction to VBA
In “Introduction to VBA” you were introduced to several key elements about VBA and
Macros. This lesson specifically focused on how to use Recorded Macros to simplify and
automate repetitive daily tasks. You learned what VBA is and how it’s an integral part of
the Office environment. Most importantly you learned how to record macros and replay
them.
Review Questions
1. What is the difference between Macros and VBA?
a. __________________________________________________
b. __________________________________________________
2. Why would you want to record a macro vs. writing VBA code yourself?
a. __________________________________________________
3. Give some examples of procedures you could record and replay.
a. __________________________________________________
b. __________________________________________________
4. Name three ways you can run a macro you’ve recorded.
a. __________________________________________________
b. __________________________________________________
c. __________________________________________________
5. What should you always do before running a macro?
a. __________________________________________________
Case Study
A major hotel chain reduced
workflow from their
properties to the Accounting
Department by creating an
automated night audit
report that could be
uploaded directly into their
accounting system.
Previously the reports were
filled out by hand, faxed to
Accounting and manually
entered each day.
Excel 2010 - Introduction to VBA Programming 15
Lesson Assignment: Introduction to VBA Your first assignment is to open a new Excel document and start recording some macros. If you feel comfortable enough then by all
means work on a copy of personal workbook and record some tasks with which you’re familiar. Practice adding a Macro to the
Quick Action Toolbar (QAT), as well as assigning them to some objects. (There is a Notes section below for you to keep track of your
observations):
Introduction to VBA: NOTES