Escolar Documentos
Profissional Documentos
Cultura Documentos
The problem:
A programmer wants to learn how to program in Microsoft Visual Basic for
Applications.
The context:
The programmer has seen Visual Basic and VBA code, but is not very familiar with
the syntax, and is not very familiar with the objects that are commonly used in VBA
code. The programmer has seen some TestFirst code, but has not learned how to
test her own code first. The programmer is not familiar with VBA's environment for
trying out individual lines of code, and does not have much practice stepping
through VBA code in the debugger. The programmer does have experience
identifying a problem, identifying what a solution to the problem should be capable
of, and verifying that the solution matches the problem requirements -- just in other
contexts. The programmer has reference material for VBA (including VBA's help, the
help within each Microsoft Office application, Google, and a very thick reference
tome). The programmer has access to the Refactoring book, which unfortunately
only has Java examples. The programmer has access to an experienced VB and VBA
programmer, whom she can ask questions of. The programmer has access
to MicrosoftOffice, includingMicrosoftWord, MicrosoftExcel, and MicrosoftAccess.
What this page tries to do:
This page will present a series of programming exercises. Each exercise will allow the
programmer to become familiar with one feature of VBA. By the time the
programmer is done with the exercise, the programmer will be able to explain the
concept, when it is useful, when it is not useful, and what some common problems
are with it. The programmer will have used the concept to solve a problem of her
own devising. The exercises will build on each other, and let the programmer
continually refresh and cement her knowledge of the earlier concepts. In other
words, it will use the SaxonMath? approach, not the CramStudying? approach. This
page will not present the answers to the problems -- those are left as exercises for
the programmer. (Per the context, the programmer can get the information she
needs to solve the problems.)
Recommended Coding Conventions:
In each of the exercises, it is a very good idea to follow these guidelines:
Always use Option Explicit
Always explicitly state whether a Sub, Function, or Type is Public or Private.
Always
explicitly
state
whether
an
argument
to
a Sub or Function is ByRef or ByVal.
Use the line continuation character to explicitly wrap long lines. This lets you
see all of your code in the IDE, and see it the same way when you print out.
Whenever possible, declare variables with a datatype; avoid implicitly
declaring them as Variant. If a variable needs to be a Variant, know why it
needs to be a Variant.
Exercise 1: The Excel VBE
In Excel, launch the VisualBasicEditor? (VBE).
Configure the VBE so that any new modules you create start with Option
Explicit.
In the VBE, show these features:
o The Project Pane
o The Immediate Window
o The Locals Window
o The Code Window
Write a line of code in the Immediate Window that computes something. For
example, if you have 3 spoons and 4 forks, how many pieces of flatware do
you have in all? Make VBE show you the result in the Immediate Window.
Optionally, exit VBE.
Optionally, exit Excel.
Questions about Exercise 1:
o What is the purpose of the Project Pane?
o What is the purpose of the Immediate Window?
o What is the purpose of the Locals Window?
o What is the purpose of the Code Window?
o What are the two ways you can tell the Immediate Window to show
you an answer in the Immediate Window?
Exercise 2: The Access VBE
Perform Exercise 1 in Access.
Questions about Exercise 2:
o How are the contents of the Project Pane different in Access than in
Excel?
Exercise 3: "OK" Message Boxes
o
o
o
If you do not specify Public or Private, what does VBA default to?
Why should we always explicitly specify Public or Private?
How do you tell VBA what value should be returned by a function?
Make it so that updating the first cell automatically updates the second cell.
(This is trivial -- just have a formula in the second cell that gets the value from
the first cell.)
Make it so that updating the second cell automatically updates the first cell.
(This is trivial, if you are willing to give up the ability to manually change the
first cell -- just have a formula in the first cell that gets the value from the
second cell.)
Create Worksheet_Change() event(s) for each cell.
o Have each Worksheet_Change() event call a subroutine -- but do not
make the subroutine set the value of the other cell yet. (If you do, you
risk an infinite loop).
o Use a static variable inside the subroutine to make sure that the guts of
the subroutine do not get called (indirectly) by the subroutine. You will
need to use a GuardClause, as discussed in Exercise 10.
o Now it is safe for the guts of the subroutine to set the values of both
cells.
Save your work.
Exercise 18: Text Box Events
In an Access database, create a form.
On the form, create two text boxes.
When the text in the first text box changes, update the second text box.
Save your work.
Questions about Exercise 18:
o What are the differences between using macros and code to perform
this update?
o What events can you use to trigger this update?
o When do these events occur?
o What order do these events occur in?
o Does triggering one of these events require triggering another event?
For example, single-click versus double-click.
For example, leaving one control and entering another control.
o Can you think of scenarios where you might want to use some of these
events?
o Are there any events where it is hard to think of scenarios that should
use them?
o Do any of your scenarios result in infinite loops?
o
o
o
o
o
o
o
When would you want to use an "Abort / Retry / Cancel" dialog box?
Is it easy for the user to understand these choices? Why or why not?
What ways are there around this problem?
What should the program do if the user closes the dialog box from the
dialog box' toolbar?
What does the program do if the user closes the dialog box from the
dialog box' toolbar?
Using the Worksheets() collection to get the worksheet object that has
a particular name
o Ways to tell a subroutine to update a particular worksheet
Passing the worksheet object
Passing the name of the worksheet
Passing the number of the worksheet in the collection (not
recommended)
Optimizations
o Reducing the flashing of the code that hides rows
String manipulation -- Left(), Right(), Mid(), Len(), InStr?(), Trim()
How to avoid errors when using these functions
Newer string functions
o Reversing strings
o Searching backwards in a string
o The Like operator
Common data types
o When to use Int or Long
o When to use Float or Double
o When to use String
o When you have to use Variant
Inputs from Excel that might be either a number or a string
Inputs from Access that might be Null
Passing objects (such as worksheets or cell ranges)
Passing pointers to/from Windows API calls
Switch statements in Access' SQL view
Iff statements in Excel's formula bar
Ways to find things in the help system
o F1 is sometimes context-sensitive
o The Language Reference
What is a collection or an object?
The differences between methods, properties, events, and
functions
What is an enumeration?
o Finding things in the help
o Google
Good habits when you work with someone else's code
o Giving credit for code found on the Internet
Good naming habits
o Name objects based on what they are
o
Name functions and subroutines based on what they do. If you were to
yell at the computer to do something, what would you yell?
o We are in the VowelGeneration -- it is good to be able to pronounce
your variable names, functions, and subroutines.
Optionally:
o Either consistently use VB's simplified HungarianNotation
o Or consistently do not use HungarianNotation
o
Discussion:
Re: "Whenever possible, declare variables with a datatype" + Re: "Always explicitly
state [...] Public and Private"
This is the "heavy typing" view of things rather than the scriptish "keep code short
and clean" philosophy. Perhaps the verbose approach is good during the learning
phase, but dynamic coding is a useful and powerful skill and this should be pointed
out. (This doesn't apply to "option explicit", which MS screwed up badly on.) --top
The "verbose approach" is also good when the requirements prioritize
static TypeSafety over terseness.
Well, okay. I just think the beginner should know about both styles and that they
both have their place. Even if you personally "hate" one or the other, a beginner has
to at least be ready for the different expectations and requests of the marketplace.
True, but I'd encourage beginners to especially avoid implicit Variant variables in
order to discourage questionable practices, such as using the same variable for
multiple, differently-typed purposes in the same code block. Arguably, "scriptish"
approaches using dynamic implicit typing should be considered an advanced
programming technique -- a sharp cutting tool for the expert, rather than a shortcut
for the beginner. New VBA programmers are all too likely to cause run-time type
errors due to careless or nave "beginners" coding. Manifest static typing may help
reduce the likelihood of this, whilst encouraging discipline and focusing the
developer's mind on the type and purpose of a given variable.
Students should be exposed to dynamic typing at some point. Perhaps VBx is not the
best language for such because of its messy rules and limiting declaration options.
See also:
VbClassic, VisualBasicForApplications, VbClassicSurvivalGuide,
MicrosoftOffice, MicrosoftAccess, MicrosoftExcel, TeachMeToSmoke
MsgBox, GuardClause, SingletonPattern, SelectCaseExamples