Powerful PowerPoint For Educators
Powerful PowerPoint For Educators
Powerful PowerPoint For Educators
David M. Marcovitz
LIBRARIES UNLIMITED
Powerful PowerPoint
for Educators
David M. Marcovitz
List of Figures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Chapter 1: Multimedia Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Vocabulary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What Is Multimedia? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
The Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Project Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Metaphors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Storyboards and Flowcharts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Designing Assignments for Your Students . . . . . . . . . . . . . . . . . . . . . . . . 8
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Chapter 2: Traditional Multimedia Features of PowerPoint . . . . . . . . . 13
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Vocabulary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Inserting Pictures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Linking and Embedding Sounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Are My Sounds Linked or Embedded? . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Hypertext Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Buttons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Text for Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Sound for Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Controlling Navigation with Kiosk Mode . . . . . . . . . . . . . . . . . . . . . . . 29
Saving As a PowerPoint Show . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Exercises to Try . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Chapter 3: Introducing Visual Basic for Applications . . . . . . . . . . . . . . . 33
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Vocabulary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
What Is Visual Basic for Applications? . . . . . . . . . . . . . . . . . . . . . . . . . 34
What Is an Object-Oriented Programming Language? . . . . . . . . . . . . . . 35
VBA and Viruses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Exercises to Try . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
viii Contents
Epilogue. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
List of Figures
9.4 VBA Editor Suggests Parameters for the GotoSlide Method . . . . . 166
9.5 VBA Editor Suggests Parameters for the AddShape Method . . . . . . 167
By the time you finish Chapter 9, you will be excited to create things your-
self, but you might want to share your knowledge with your colleagues and your
students. Some of them will share your enthusiasm and borrow your copy of this
book (or better yet, buy their own copy) and dive right into powerful
PowerPoint. Others won’t be ready for the technical challenge. Chapter 10 de-
scribes how you can use templates, so your colleagues and students can take full
advantage of the power of VBA scripting without knowing any of it. You can
use what you learn in Chapter 10 to provide a template for your colleagues or
students with the scripting already done for them (by you).
When you have completed the book, you might not be an expert at using
VBA to create powerful interactive multimedia projects, but you will have a
large bag of tricks that can help you do more with technology to make you a
better educator.
Writing this book has been a long process. I began my journey when I at-
tended a presentation at a conference in which the speaker was talking about all
the exciting educational things that can be done with PowerPoint. I thought that
he was talking about the things this book discusses, but I was wrong. I started ex-
ploring, and I found that no one was talking about these things, at least not for
educators. As I looked for books to help me, I found many (look in the Refer-
ences section at the end of the book), but none was geared to educators or to us-
ing PowerPoint interactively. I wanted to share this with my students, so I started
creating my own handouts. As the handouts grew, I began speaking about this at
conferences and giving workshops. Everyone was amazed at what PowerPoint
could do. By the time the handouts reached seventy pages, I knew it was time to
move from handouts to a book.
I would like to thank all the people who helped me along the way, but they
are too numerous to mention, so I will mention only a few. I would like to thank
all my students over the years in Multimedia Design in the Classroom, particu-
larly the first group, who had to endure the course with a few pages of handouts
that were being written during the course, in most cases the night before each
class. I also would like to thank Diana Sucich, one of my students who reviewed
the manuscript as it was morphing from a seventy-page packet of handouts into a
book. Her comments were invaluable. I also would like to thank Luis Bango, a
former student who suffered through Multimedia Design in the Classroom while
the handouts were not in the best shape and reviewed the final manuscript. I also
would like to thank the PowerPoint MVPs in the Microsoft PowerPoint
newsgroup. Several PowerPoint experts give their time in that newsgroup to an-
swer questions from beginners and experts alike with beginning PowerPoint
questions and complex scripting questions.
Finally, I would like to thank my family. My wife Emily has provided me
with unending love and support as I have stayed late in the office to work on the
book. My daughter Ella has been a guinea pig for some of my wacky projects,
particularly the example at the end of Chapter 9. Both my children, Ella and Ada,
have provided me with love and inspiration because I hope that my work will
Preface xix
help my children and all children by making the computer a more effective tool
for education.
You are about to embark on a great journey. At times you will be elated and
at times frustrated. If you persevere, you will have the power to make the com-
puter do what you want it to, so it can be a tool for you and your students’ learn-
ing. The computer shouldn’t be everything in education, but when it is used, it
should be used powerfully and effectively.
1
Multimedia Design
Introduction
Welcome to the world of powerful PowerPoint. This book will help you use
PowerPoint in ways you never thought were possible, with the ultimate goal of
creating better learning environments for your students. Whatever you do as an
educator requires some planning, whether it takes the form of detailed lesson
plans or a few notes jotted on the back of a napkin. When creating complex
learning environments, planning is very important. This chapter introduces
some of the basics of planning and design to help you create better learning envi-
ronments. You will be introduced to the benefits of multimedia, the design pro-
cess, benefits of having your students design multimedia, and metaphors and
organizations for multimedia projects.
Vocabulary
• Decide • Metaphor
• Design • Organization
• Develop • Storyboard
• Evaluate • Summative evaluation
• Formative evaluation
2 Multimedia Design
What Is Multimedia?
Multimedia is a term that has been around for a long time. Before comput-
ers, it referred to a combination of slides (from a slide projector) and sounds
(usually music from a tape player). It has been around for so long because people
have recognized that we can be engaged through multiple senses. Some people
are primarily visual learners, auditory learners, or kinesthetic learners, but most
of us are a combination of all three. Using different senses increases attention,
motivation, and, in many cases, learning. “The power of multimedia and
hypermedia presentation software comes with changes in the ways teachers and
learners have access to and demonstrate their understanding of knowledge, mov-
ing from a single dominant presentation and demonstration style (verbal/linguis-
tic, linear/sequential) to an integrated, multisensory learning and demonstration
‘microworld’ (Papert, 1992), where learners have more freedom of choice in the
mode of learning and the order in which learning takes place” (Male, 2003, p. 6).
As this quote suggests, multimedia involves multiple senses and a degree of
learner control and choice.
Robinette suggests, “Multimedia is about combining sights, sounds, and
interactive elements to create an experience unlike that which comes from sim-
ply reading text or idly viewing a video” (1995, p. 10). Goldberg says, “Multi-
media, as I use it to define the cool new medium that I’ve been going on about, is
the combination of audio/visual media elements with interactivity. . . . A typical
multimedia title might include any combination of text, pictures, computer
graphics, animation, audio, and video” (1996, p. 14).
Multimedia is about including a variety of media with interactivity. Typical
presentations (using PowerPoint or other presentation tools) emphasize the me-
dia and not the interactivity. When enhancing a lecture to present to an audience,
interactivity is not always important. However, when creating projects that your
students can control, picking and choosing where to go within the project,
well-designed interactivity is very important.
Interactive multimedia helps students learn by increasing motivation, by
giving them control over their learning, and by reaching them through different
senses. As you design multimedia presentations for your students, you decide
what media are most appropriate. Sometimes a picture is worth a thousand
words; sometimes a few words are worth a thousand pictures; and sometimes, in
the case of a struggling reader, for example, spoken words are more important
than everything else. A few bells and whistles, used sparingly and appropriately,
can increase motivation and hold your students’ attention, but a carefully de-
signed project with appropriate media elements can be a powerful experience for
the learner. The key is to design your projects well.
The Design Process 3
Don’t be afraid to brainstorm ideas. That means that you can come up with
ideas for what you want to include that will be rejected later. This is part of the
power of planning. If you create half your project first, you have either locked
yourself into something that might not be what you want, or you have wasted a
great deal of time creating something that you will throw away. By playing with
ideas in the early stages of the design process, you can narrow down what you
want to do without throwing away large amounts of work.
While you are deciding what the project should include, research your sub-
ject. Be sure you understand the subject so you can create something that will
help others learn it. As you research, you should decide what information you
want to include and begin to collect the media you will use to represent that
information.
As you decide, keep in mind that your decisions are not set in stone. You
should complete the decide phase having a good idea of what you want to do, but
you should understand that the details can and will change as you move forward
with your project.
Once you have an idea about what your project will entail, you should be-
gin to design it. You will design the organization and metaphor for the project
(more about this in the next sections), you will create a storyboard for the project
to help you understand the flow and interaction of the project, and you will de-
sign the individual slides, figuring out what content and media go on each slide.
Now your project is taking shape, and you should have a fairly clear picture of
what the final project will look like. But again, this is not set in stone. The details
can and will change, but they should change within the overall framework you
have designed.
Next, it is time to develop your project. This involves filling in the pieces:
creating or acquiring any media elements you need, creating your slides, placing
your media elements and buttons on your slides, and linking it all together. This
is much easier when you know what you want to do, having decided on the pro-
ject and having designed the project first. The hardest part will be writing your
scripts to make the project do what you want it to do, and you will learn how to
do that beginning in Chapter 3.
The final phase is not really the final phase: evaluate. Evaluation is a con-
tinuous and ongoing process. You will conduct formative evaluation, in which
you check your work to make sure that everything seems to be doing what you
want, and you enlist others to check your work as well. This can happen at many
different points in the process, and it can be done by many different people, in-
cluding: you, your colleagues, your students, and other members of the intended
audience for the project. This formative evaluation will provide you with
feedback to improve the project.
You also will conduct summative evaluation when the project is complete.
As with any lesson, you want to think about specific ways you will know how
well the project worked with your students. This can be used to decide whether
Project Organization 5
or not you want to use the project again, and it can provide feedback for things
you might want to change about the project for next time.
Project Organization
As part of the design process, you must think about how your project will
be organized. Chapter 2 describes how to create hyperlinks in PowerPoint, and
Chapter 6 describes how to use VBA to move from any slide to any other. How-
ever, just because you can make links from any slide to any other doesn’t mean
that you want to. A project with a clear organization will help your students find
their way around the project.
There are several ways to organize a project. The simplest organization is
linear, in which the user goes from one slide to the next to the next to the next
(see Figure 1.1). This works very well for projects in which knowledge is being
built from prerequisite knowledge or in which specific steps are followed in a
specific order.
However, many projects don’t require a linear organization and would ben-
efit from some other organization. Fortunately, hypermedia allows us to link any
slide to any slide that we want. We could follow a menu organization (see Figure
1.2, page 6). This organization allows the user to study the topics in whatever or-
der he or she wants and even allows the user to skip topics.
Some topics lend themselves better to a hierarchical menu structure in
which each subtopic has its own menu. Other projects might do better with a
completely hyperlinked organization in which any slide can lead to any other
slide.
The organization you choose should match the objectives of the project. If
it is not appropriate for students to skip sections, don’t allow it. You provide
links where you want your students to go (and in Chapter 2, you’ll learn about
Kiosk mode so you can make sure they only go where you want).
There are many potential structural organizations, but it is helpful to pick
something that will allow the user to navigate easily through your information. If
the structure is not easy to navigate, when a user goes through your presentation,
it is easy to get lost in hyperspace.
Figure 1.2. Menu Organization
Storyboards and Flowcharts 7
Metaphors
A metaphor is the way the user will think about the project. For example, a
geography project might choose a map metaphor where users click on certain lo-
cations on a map to visit the location. You might choose a book metaphor, start-
ing with a cover and a table of contents and referring to each slide as a page
(complete with page numbers and graphics that make the slides look like pages).
Metaphors can be complex or simple, with more complex metaphors providing
somewhat of an illusion that the user is actually in the metaphor. For example, a
travel metaphor might include animations of planes taking off and landing to
give the illusion that the user is actually going someplace.
Metaphors can be particularly helpful when you are not creating a project
but are assigning your students to create a project. This helps students to “un-
leash their creativity by finding new metaphors for information. Metaphors
stimulate visualizations” (Agnew, Kellerman, and Meyer, 1996, p. 121). Meta-
phors are a powerful tool to help users navigate a project and to help designers
think creatively about a project.
This will help you adjust your design as you need to. It is much easier to move a
card or add a card or delete a card than it is to take a half-finished project, includ-
ing VBA scripts, and move everything around, rewriting the scripts to match the
redesign.
This does not mean that your design is fixed once you start developing your
project. But with a good idea of how the project works and most of the details in
place, you will find it easier to create the project and make changes as needed.
help students understand what they are supposed to do and help them meet and
exceed your expectations. Be sure to match the project you assign to your curric-
ular goals and the technical skills of your students. If you plan to have students
create several multimedia projects, you can make the first project simple to help
them understand the technology. As their technology skills grow, the projects
can be more complex.
Many students need concrete examples. The more multimedia you do (for
yourself or your students), the more examples you will have to show students.
You also want to encourage creative thinking, including brainstorming
ideas for metaphors. A metaphor helps a user navigate through a project by giv-
ing the user something from the real world to relate to what the controls (such as
buttons and hypertext links) do. Metaphors can be closely related to the project
or can be an unrelated navigation and visualization tools. You can provide your
students with a metaphor (this might be appropriate for early projects), you can
brainstorm different metaphors for different projects as a class, you can brain-
storm with groups about metaphors for a specific project, or you can have groups
brainstorm on their own.
Finally, you will want to help your students with the design process. Stu-
dents might need help with all the design steps. You can give your students help
with all of the following:
• The Idea—A good assignment will have a clear set of objectives,
but it might allow students a great deal of latitude in picking a topic.
You might need to work with students to help them generate ideas
for their topic.
• The Research—Since one purpose of multimedia projects is to en-
hance learning in curricular areas, you will have to decide how much
of the research you will provide for the students. You could provide
all the information that will be used in the project. You could pro-
vide specific resources for students. You could help students find
materials (in the library or on the Internet, for example). You could
brainstorm ideas with students about where they might find the
information they need.
• Selecting Information—Many students have trouble finding
enough information, and many have trouble selecting the informa-
tion to include. You might need to help students narrow down the
appropriate information to include; they might not be able to include
everything they find.
• The Organization and the Metaphor—You might pick an organi-
zation and a metaphor for your students or help them find an appro-
priate organization and metaphor.
10 Multimedia Design
Conclusion
This chapter has given you a brief introduction to multimedia, including
what it is and what its benefits are, and has introduced you to the design process.
If you plan carefully, you will save yourself time and limit frustration, and you
will create better projects. Finally, the chapter introduced some ideas for having
your students be multimedia designers. This chapter was an introduction to,
rather than complete coverage of, the design process. You might want to check
Conclusion 11
out Ivers and Barron (2002) or Agnew, Kellerman, and Meyer (1996), which
provide more details about the design process and using multimedia with
students.
Now that you have a basic understanding of the design process, you are
ready to apply it to PowerPoint. The next chapter introduces some of the interac-
tive and multimedia features of PowerPoint and prepares you to conquer the ad-
vanced scripting features of PowerPoint in later chapters.
2
Traditional Multimedia
Features of PowerPoint
Introduction
Some people, even long-time PowerPoint users, are not aware of many of
the multimedia and interactive features of PowerPoint. Most of this book de-
scribes how you can use scripting features of PowerPoint to make presentations
interactive. This chapter briefly describes some of the multimedia and interac-
tive features that do not require scripting. You will learn about media elements,
such as pictures and sounds, and you will learn about interactive elements such
as hyperlinks and action buttons. In addition, you will learn about the important
differences in Slide Show View and Edit View when editing your slides. Finally,
you will learn about Kiosk mode and saving your project as a PowerPoint Show
to control how your students navigate through your presentation.
Vocabulary
• Action buttons • Hyperlinks
• Clip art • Hypertext
• Copyright • Kiosk mode
• Edit View • Linked
• Embedded • PowerPoint Show (.pps)
• Fair use • Slide Show View
14 Traditional Multimedia Features of PowerPoint
Next, click on the Edit tab. Find the “Undo” section. Change the setting for
“Maximum number of undos” to 10. In many applications, when you make a
mistake, if you don’t do anything else, you can fix it by choosing “Undo” from
the Edit menu. In PowerPoint, you can fix not only the last mistake but several
mistakes before that. This setting tells PowerPoint how many things it has to re-
member so you can undo them. In theory, you might want to have as many as
possible, but several PowerPoint experts have noticed that the higher this num-
ber is the more likely you are to have problems with PowerPoint. Setting it to 10
gives you enough ability to correct your mistakes while minimizing the likeli-
hood that you will have a problem.
Another setting you might want to change can be found under the General
tab. You might want to change the setting for “Link sounds with file size greater
than.” This setting is discussed later in this chapter.
Once you have changed the settings to not allow fast saves and to limit the
number of undos, click OK to save the settings.
Next, choose “Customize” from the Tools menu. Click on the Toolbars tab
and make sure there is a check next to “Drawing.” The “Drawing” toolbar will
be very useful for drawing your own shapes and modifying the appearance of
shapes that are drawn for you.
Finally, before you start working on a PowerPoint project, create a folder
on your disk for your project and save your presentation to that folder. This will
be important when you start including hyperlinks and multimedia objects in
your presentation. Most elements of your presentation will be embedded in your
presentation. That is, they will be part of the PowerPoint file. Other elements
will be stored in other files, and your presentation will link to those other files. If
you save your presentation first and you save any linked files to the same place
you save your presentation (that is, the same folder on the same disk), your links
will continue to work when you move the presentation (along with all the linked
files) to another place, such as another folder, another disk, or another computer.
If you don’t save your files first, the links are likely to stop working.
Inserting Pictures
You can insert pictures into a PowerPoint presentation in several different
ways, including by inserting from the clip art library, by inserting from an exist-
ing file, and by copying and pasting from another place, including the World
Wide Web. In addition, if you are artistically inclined, you can use the drawing
tools to draw your own pictures. Generally pictures are embedded in your
PowerPoint presentation. That is, once you insert them, they become part of the
presentation, regardless of what happens to the original picture.
PowerPoint recognizes many different types of picture files, including
most of the common ones you are likely to encounter, such as Graphic Inter-
change Format (.gif), Joint Photographic Experts Group (.jpg), Tag Image File
Format (.tif or .tiff), and Bitmap (.bmp). If you try to insert a picture into your
16 Traditional Multimedia Features of PowerPoint
presentation and PowerPoint gives you an error or asks you how to convert it,
you will need to find a program (such as GraphicConverter™ or Adobe
Photoshop™) that can read that file type and create files of one of the types that
PowerPoint can read.
To insert a picture from a file, choose “Picture” from the Insert menu and
choose “From File . . . ” from the flyout menu (see Figure 2.2).
Figure 2.2. Choosing Insert Picture From File from the Menu
Although the dialog box you see will vary slightly depending upon which ver-
sion of PowerPoint you are using, it should look similar to the dialog box you see
whenever you try to open a file on your computer. From this point, locate the file
with the picture you want to insert and click on the “Insert” button.
While inserting a picture from a file has remained fairly consistent from
version to version of PowerPoint, inserting clip art has changed quite a bit. You
start by choosing “Clip Art . . . ” from the flyout menu instead of “From File . . . ”
(see Figure 2.2). In PowerPoint 2002, you can search for clip art using the dialog
shown in Figure 2.3, use the Clip Organizer, or search Microsoft’s fairly exten-
sive collection of clip art on the Web. From Microsoft’s Web collection, you can
download clip art into your own collection so you can use it later without going
to the Web.
Inserting Pictures 17
Another way to add graphics to your presentation is to copy and paste. Gen-
erally, if you can see it on your computer you can copy it into your presentation.
However, you must be careful; although you might be able to copy a picture into
your presentation, you might not have the right to copy it into your presentation.
Be sure to follow copyright law and guidelines, noting that just because you
don’t see a copyright symbol © does not mean that the picture or Web page is not
copyrighted. While the fair use aspects of copyright law give you a great deal of
freedom to use copyrighted material for educational purposes, many restrictions
apply as to what you can use, how much you can use, and for how long you can
use it. Your best bet is to use material you have created yourself, material that is
in the public domain (see for example, http://www.pics4learning.com/), or ma-
terial for which you have obtained permission to use. But if you must use copy-
righted material without permission, you should pay close attention to the Fair
Use Guidelines for Educational Multimedia (see http://www.utsystem.edu/ogc/
intellectualproperty/ccmcguid.htm). While these guidelines are not the law, they
are a good guide for your fair-use rights to use copyrighted material.
If you are on the Web and you see a picture that you want to use and you
have the right to use it because of fair use, because the picture is in the public do-
main, or because you have permission to use it, you can generally copy it into
your PowerPoint presentation. If you are on a Macintosh, point your mouse to
the picture you want to copy and hold the mouse button down until you see a
18 Traditional Multimedia Features of PowerPoint
menu that pops up. If you are on a Windows computer, point your mouse to the
picture and right click (that is, click the right mouse button; see Figure 2.4).
The flyout menu that you see should look something like the menu in Fig-
ure 2.5. It will vary from browser to browser, but you should see “Copy” as one
of your choices. Choose “Copy” (by clicking or left clicking on the choice in the
menu). Now, when you switch back to your PowerPoint presentation, you can
choose “Paste” from the Edit menu to put the picture in your presentation.
Once a picture is in PowerPoint, it is an object, and you can move it around,
resize it, or even assign it actions. Pictures are always embedded in the presentation,
so you don’t need the original picture file to see the picture within PowerPoint.
Sounds
PowerPoint presentations can include sounds in a wide range of formats.
Like pictures, the sounds can be inserted from clip art or from a file. Sounds can
also refer to a CD track or be recorded, assuming you have a microphone con-
nected to your computer. You can make the appropriate selection by choosing
“Movies and Sounds” from the Insert menu.
If you choose to use a CD track for your sound, then the CD must be in the
computer when you are inserting the sound and whenever you are running the
presentation. This works well if you are presenting something to an audience,
but it works poorly if you are putting the presentation on several computers for
your students. A better alternative might be to import the CD track into your
computer, but you must be careful about copyright guidelines, which limit the
amount of a song you may use to 10 percent of the song or thirty seconds,
whichever is less.
Sounds 19
sound is linked, there is a good chance that the sound will not play on other com-
puters. To alleviate this, you should find out where the sound is located on your
computer and copy the sound you intend to use into your folder with the presen-
tation. On my Windows computer, many of the standard clip sounds can be
found in the folder: “C:\Program Files\Microsoft Office\media\CntCD1\
Sounds,” but that is unlikely to be where they are on your computer. On my
Macintosh, the standard clip sounds can be found in “Macintosh HD:Applica-
tions:Microsoft Office X:Office:Sounds.”
Hypertext Links
Before version 97, PowerPoint was simply a tool to present material. Pre-
senters would stand up in front of an audience and go through slide after slide.
PowerPoint’s advantage was that media (text, graphics, sounds, videos, etc.)
could be incorporated into the presentation to add bells and whistles and to pres-
ent information in a variety of formats. PowerPoint 97 changed all that. OK,
PowerPoint 97 changed very little of that because most people still use
PowerPoint for linear presentations. However, PowerPoint 97 allows you to use
it in different ways.
One tool that was added to PowerPoint was hyperlinks. Hyperlinks allow
you to create presentations that are nonlinear. With the popularity of the World
Wide Web, everyone is used to clicking on text to jump somewhere, and
PowerPoint gives you that capability. You can create hypertext links to other
places in your presentation, to Web pages, and to other files.
the next to the next to the next. You can make them go anywhere. If you are giv-
ing a presentation, you might want to link to slides with the answers to questions
you anticipate being asked. If you are creating something for your students, you
might use a menu structure in which students choose a topic from a menu and
when finished with that topic, jump back to the menu.
To link to another place within your PowerPoint presentation, create a few
slides first, perhaps creating a menu slide that will link to the other slides. High-
light the text you want to link and choose “Hyperlink” from the Insert menu. Be
sure to highlight the text; if you don’t, PowerPoint will make a single word the
link. See Figure 2.7.
The exact format of the dialog box that you see will vary based on which
version of PowerPoint you use, but it should look very similar to Figure 2.8 or
Figure 2.9.
Hypertext Links 23
In some versions, you will see tabs for “Web Page,” “Document,” and
“E-mail Address” (see Figure 2.8). In other versions, you will see tabs for “Ex-
isting File or Web Page,” “Place in This Document,” “Create New Document,”
and “E-mail Address” (see Figure 2.9). To link your text to another slide, choose
“Document” or “Place in This Document.” If your screen looks like Figure 2.8,
click on the “Locate . . . ” button in the “Anchor” section of the dialog box. Now
your screen should look like part of Figure 2.9 with choices to link to “First
24 Traditional Multimedia Features of PowerPoint
Slide,” “Last Slide,” “Next Slide,” “Previous Slide,” “Slide Titles,” and “Cus-
tom Shows.” If you don’t have any choices for slides under “Slide Titles,” click
on the triangle or plus sign next to “Slide Titles” and the names of all your slides
should appear. This is where you can choose a particular slide to link to. Click on
the slide title to which you want to link and click OK. The highlighted text
should become underlined and change color (based on the colors in the template
you are using).
Some of you tried to click on your text, and it didn’t take you anywhere.
That’s OK. As you know, PowerPoint has different views or modes in which
you can see your slides. We can edit our slides in Edit View (sometimes called
Normal View), but we run our presentation in Slide Show View. Our links will
only work in Slide Show View. Choose “View Show” from the Slide Show
menu to take you into Slide Show View (that’s the view where you only see your
slide on the screen with no menus or toolbars). Now you should be able to click
on your hypertext link to take you to another slide. You’ll notice that when you
point to a hypertext link (or any element of PowerPoint on which you can click),
your cursor changes from an arrow to a hand. Watch for that change in Slide
Show View so you can see what is clickable and what is not.
Once you have linked one part of a menu, it is easy to follow the same steps
to link the rest of the items in the menu: Highlight the text you want linked,
choose “Hyperlink . . . ” from the Insert menu, choose “Document” or “Place in
This Document,” click on the plus sign or triangle if necessary to see the titles of
your slides, click the appropriate slide title, and click OK.
will have to copy the URL and paste it into PowerPoint. Note that if you have to
paste and your Edit menu isn’t active, you usually can use the keyboard shortcut
(control-V in Windows or command-V on a Macintosh) to paste.
To link to another document, choose the “Document” tab in Figure 2.8 or
“Existing File or Web Page” in Figure 2.9. Click on the “Locate . . . ” button or
the “Browse for File” icon (it looks like an open folder with an arrow opening it)
to get the standard Open File dialog box. In Windows, you might have to pick
files of type “All Files” to be sure you can see documents that PowerPoint does
not recognize.
Note that when you are choosing a file, you are creating a link. Just like
linked sounds, if you want PowerPoint to be able to open the document when the
presentation is moved to another computer, you should put the file in the folder
with your PowerPoint file before linking to it.
Buttons
Sometimes you want your users to click on text to follow a hyperlink, and
sometimes you want them to click on a button. PowerPoint provides buttons
with a few different icons for different purposes. Choose “Action Buttons” from
the Slide Show menu, and a flyout menu will appear with either icons for buttons
or names of buttons. Figure 2.10 shows the twelve different kinds of buttons:
Custom, Home, Help, Information, Previous Slide, Next Slide, First Slide, Last
Slide, Last Slide Viewed, Document, Sound, and Movie.
The button icons do not have to correspond to the action the button will per-
form, but good rules of design dictate that the icon should make sense for what is
going to happen when the button is pressed.
Once you select a button (from the flyout menu from “Action Buttons”),
your cursor will change to a plus sign. You can either click on your slide and a
standard size button will appear, or you can drag the mouse to create a button of
26 Traditional Multimedia Features of PowerPoint
any size you like. Don’t worry if the size isn’t perfect; you can always click on
the button and drag it from the handles to change the size.
Once you create the button, you will be prompted with the dialog box
shown in Figure 2.11.
This dialog box allows you to have your button do many of the same things you
could do with a hyperlink. Unfortunately, the same things are done in a slightly
different way.
To link to another slide, you will choose “Hyperlink to” and pick from the
drop-down menu. If you chose an icon for your button, “Hyperlink to” might al-
ready be chosen with PowerPoint’s best guess for what you want to do. If
PowerPoint guessed correctly, just click OK; otherwise pick something else.
Like the hyperlinks for text, you can choose “Next Slide,” “Previous
Slide,” “First Slide,” “Last Slide,” and “Custom Show.” You can also choose a
specific slide by choosing “Slide . . . ,” which will prompt you for the slide to link
to.
In addition to the choices that were available for hyperlinks for text, you
can also choose “Last Slide Viewed,” which takes you to the slide that took you
to the current slide. Imagine a quiz with several questions. Each wrong answer
leads to a slide with the word “Wrong” (or some more gentle reminder that the
Text for Buttons 27
incorrect answer was chosen) on it. The “Wrong” slide can contain a button that
returns to the last slide viewed, so it always returns to the question that was just
answered, no matter which question that is. Another additional option is “End
Show,” which will quit out of Slide Show View.
The “URL . . . ” choice will allow you to type in a Web address, but it does
not give you the option to browse for a Web address. “Other PowerPoint Presen-
tation” not only lets you choose another PowerPoint file, but it also lets you pick
which slide in that presentation the button will go to. Finally, “Other File . . . ” is
just like browsing for a file when choosing “Existing File or Web Page” or
“Document” with a hypertext link.
Once you have chosen where to “Hyperlink to,” click OK. If you ever want
to change what the button does, click on the button to select it and choose “Ac-
tion Settings” from the Slide Show menu.
Remember that buttons, like hyperlinks, only work in Slide Show View. If
you click on them in Edit View, you will select them. Clicking on them in Slide
Show View will do whatever action you set the button to do.
Now that you have seen a few things that buttons can do that hyperlinks can-
not, I’ll let you in on a little secret: Any PowerPoint object, including text, can have
the same action settings as a button. If you click on a picture or a shape drawn with
the Draw tools, or you highlight text, you can choose “Action Settings” from the
Slide Show menu and get all the same options described in this section for buttons.
WARNING!
When a button has text, it is easy to change the action set-
tings for the text instead of the entire button. Your clue that
you have done this is that the text will change color and be
underlined if it has action settings associated with it. Figure
2.12 (page 28) shows a menu button that has the link associ-
ated with the text, not the entire button.
28 Traditional Multimedia Features of PowerPoint
The problem with this is that if a user clicks anyplace on the button except
the text, the button will not work. This situation can be even worse, if the button
itself has action settings to do one thing, and the text of the button has action set-
tings to do something else. If this happens, highlight the text in the button,
choose “Action Settings” from the Slide Show menu, and click “None” for the
action.
To be sure that you are setting your settings for the button itself and not just
the text, click once on the button. If you see a flashing cursor in the text, click on
the button again, but be sure to click somewhere outside of the text. Watch the
shape of the cursor for the mouse. If it is the text cursor (known as the “I bar” be-
cause it looks like a capital I), then you are clicking in the text. Otherwise you are
clicking outside of the text. Once you have selected the button, and not the text,
you can choose “Action Settings” from the Slide Show menu.
If you choose to animate text, whether or not you use Kiosk mode, you
should animate your navigation buttons as well. Have them appear on the screen
after all the text has appeared. By doing this, users won’t click a button to go to
another slide before all the text has shown up on the current slide.
Conclusion
Now you have a basic understanding of the traditional interactive and mul-
timedia features of PowerPoint. You are no longer confined to creating linear
presentations that simply go from one slide to the next to the next. You have the
full power of buttons and hyperlinks to allow for any of the designs described in
Chapter 1 and, with Kiosk mode, you have complete control over where the user
goes within your presentation. Now that you have conquered the traditional in-
teractive multimedia features of PowerPoint, you are ready for the next chapter,
which will introduce you to the advanced scripting features available to you in
PowerPoint.
Exercises to Try
Ä Create a simple tutorial with a title slide, a menu slide, and four
content sections. Put a button on your title slide to go to the
menu slide. Link the menu to each of the content slides. Include
a button on each of the content slides to return to the menu. Put
your tutorial in Kiosk mode and save it as a PowerPoint Show.
See Figure 2.15.
Introduction
In Chapter 2 you learned some of the traditional multimedia features of
PowerPoint, such as pictures, sounds, hyperlinks, and action buttons. These are
important features of PowerPoint, and even if you become a VBA expert, you
will use these features over and over again. But you might be wondering what
VBA is and what it can do for you. This chapter explains what VBA is, describes
how VBA fits into the world of object-oriented computer languages, and re-
lieves your concerns about VBA and computer viruses.
Vocabulary
• Class • OOP
• Inheritance • Parameter
• Macro virus protection • Property
• Method • VBA
• Object • Virus
• Object-oriented • Visual Basic for Applications
programming language
34 Introducing Visual Basic for Applications
!
Note that the VBA features of PowerPoint work in all ver-
sions of PowerPoint starting with version 97, but they do
not work in the PowerPoint Viewer or when saved as a
Web page. PowerPoint presentations that use VBA can be
placed on the Web, but they must be downloaded from the
Web and run directly on a machine with a full version of
PowerPoint.
The first line says that myPhoneBook is a specific instance (an object) of
the class PhoneBook. This tells us that all the things we can do with phone
books in general can be done to this specific phone book. Since one of the things
that we can do with phone books is look up a specific person, we do that on the
second line. myPhoneBook.LookUpPerson says that for this specific phone
book, call the method (do the action) LookUpPerson. Since we need to know
which person to look up, this method takes an argument (information that the
method needs to complete its job). That information is put in parentheses after
the method. Since the information is text, we put it in quotes, too.
Computers are very picky. All the details are important. The dot (that pe-
riod between myPhoneBook and LookUpPerson) is necessary to tell the com-
puter that LookUpPerson is the thing to do (method) with the object
myPhoneBook. The parentheses tell the computer that the stuff inside is impor-
tant information (parameters) for knowing what the method should do. The
36 Introducing Visual Basic for Applications
quotes tell the computer that what’s inside them is text. Leave out any detail, and
nothing will work.
Another critical point about objects is that they can have parts. Think about
our phone book example. Think about what parts there are to a phone book. Here
are a few examples: the cover, pages, the blue pages (for government listings),
and the phone company information (such as how to contact the phone company
if your phone stops working). Each of these parts is its own object (a particular
page might be an example of the class Page, or a range of pages might be an ex-
ample of the class Pages). You might access the phone book by accessing a part
of the book. For example,
myPhoneBook.Pages.TurnToTheNextPage
might take the set of pages and turn them to the next one, so if you are on page
57, for example, you will find yourself on page 59 (if the page is two-sided).
Now the dot is serving two purposes. The first dot says that Pages is a part of the
object myPhoneBook, and the second dot tells the computer to do the thing (run
the method) TurnToTheNextPage, which is something that can be done to
Pages.
While some parts of an object are other objects, some parts are properties.
For example, a phone book has a color, a number of pages, and a thickness. So
for example, if I wanted to see how thick my phone book is, I might look at that
property:
myPhoneBook.thickness
or I might want to add two thicknesses together to get something tall enough for
my daughter to sit on and be able to reach the table:
myPhoneBook.thickness + myNeighborsPhoneBook.thickness
Finally, we turn to inheritance, and then you won’t be an expert in OOP, but
you will be able to play one on TV. We have been looking at the class
PhoneBook. Well, isn’t a phone book just a specific type of book? Therefore,
we could think of a PhoneBook as a type of Book that inherits all the properties
and methods from books. The object I am working with is still myPhoneBook,
but it is not only a member of the class PhoneBook, it is (since PhoneBook is a
subclass of Book) also a member of the class Book. Everything you can do with
a book, in general, you can do with a phone book . . . and more. For example, you
can turn pages in a book, look at the cover, weigh down papers, etc. You can also
look up a phone number or find information about area codes in a phone book,
but not in all books.
Now, with this basic understanding of objects, classes, and methods, you
will be able to understand the basics of OOP when these terms come up.
Before leaving OOP, think about how it relates to PowerPoint. PowerPoint
has many objects and classes. A typical PowerPoint presentation contains many
VBA and Viruses 37
slides. Slides! That’s a class. As a class, Slides is the collection of all the indi-
vidual slides in a presentation. The set of slides in your specific presentation is
an object. That set of slides contains individual slides. A slide might contain
many objects or shapes. Think about a slide with a text box, a piece of clip art,
and a button. Perhaps these are shapes 1, 2, and 3 on the slide. They each have
many properties, such as whether or not they are visible. Because a text box, a
piece of clip art, and a button are all members of the class Shape and shapes may
be visible or not, we can look at the Visible property of these objects. For
example:
ActivePresentation.Slides(3).Shapes(2).Visible
Click this button to bring up the Macro Security dialog box (see Figure 3.3).
You can choose high, medium, or low security. If you choose high security,
you will not be able to use VBA. Medium security is probably your best choice.
You will be able to run PowerPoint presentations that contain VBA, but you will
be asked if you want to enable macros before PowerPoint opens the presentation
(see Figure 3.1). With low security, you will be able to open all PowerPoint pre-
sentations without being asked if you want to enable macros.
Exercises to Try 39
Be careful when you click on the “Enable Macros” button. If the slide show
was written by you or someone you trust, choose Enable Macros. If not, it is gen-
erally a good idea to choose Disable Macros because some unscrupulous person
might have included a virus in your file. Your students, when running your pre-
sentation, will have to choose Enable Macros.
Conclusion
You now have a basic understanding of what VBA is and how it fits into the
world of object-oriented programming languages. You also know the relation-
ship between VBA scripts and macro viruses (although you would never use
VBA for nefarious purposes). You are now ready to learn how to write VBA
scripts.
Exercises to Try
Ä If you use a newer version of PowerPoint, set your macro secu-
rity to medium or low. If you use an older version of PowerPoint,
enable macro protection.
Ä Look at a simple PowerPoint presentation that you have created
in the past. Using pencil and paper (or a drawing program or an
organization chart slide in PowerPoint), try to draw a chart of all
the parts of the presentation. Put the presentation at the top (you
can call it ActivePresentation and put the collection of
40 Introducing Visual Basic for Applications
slides below that. Under the collection of slides, put each of your
individual slides (if you chose a big presentation, just pick the
first three or four slides). Under each slide, put the various ob-
jects on the slide. See Figure 3.4 if you are having trouble getting
started. Don’t worry if you don’t get all the objects; the purpose
of this exercise is to begin to think about all the objects that you
will be able to manipulate with VBA.
Ä Pick one object from one slide and list as many properties as you
can. The purpose of this exercise is not to get a detailed list of ev-
erything about a presentation or an individual object but to start
thinking about how a presentation is organized and what proper-
ties objects might have for you to manipulate. Don’t worry if you
can’t think of all the properties (objects contain properties about
which you don’t even know) or even if your properties don’t
match PowerPoint’s “official” properties. To get you started,
think about a rectangle’s size, location, and color. You might
also select the object within PowerPoint and try to see what prop-
erties you can change (click on the object to select it, go to the
Format menu, and choose the last item in the menu, which will
be the type of object you are formatting, i.e., “Picture” if the ob-
ject is a picture, “Text Object” if the object is a text object,
“AutoShape” if the object is a drawn shape, etc.). Anything you
can change with traditional PowerPoint features you will be able
to change with VBA.
4
Getting Started with VBA
Introduction
In previous chapters you learned some basic features of PowerPoint and
what VBA is. This chapter shows you how to access the VBA Editor, how to
write simple scripts in VBA, how to attach those scripts to buttons and objects,
and how to protect your scripts with a password. When you have completed this
chapter, you will know the mechanics of writing a script and using it in a
PowerPoint presentation, and you will be ready to learn how to do some interest-
ing things with VBA.
Vocabulary
• Action settings • Module
• Add Text • MsgBox
• Button • Password
• Macro • Visual Basic Editor
left (the Project window and the Properties window) and a large blank area on
the right of the screen. Choose “Module” from the Insert menu, and you will get
a window in the blank area (see Figure 4.1). The window probably will be
named “Module1.” This is where you will write your procedures.
Note that the computer will type the “End Sub” for you. Now go to the Run
menu, and select “Run Sub/UserForm.” You should get a message box that says
Hello (see Figure 4.2).
Congratulations! You have just written and executed your first VBA proce-
dure. Click the OK button, and you can do some more.
If you don’t see Module1 in the Project window, but you do see Modules, you
should have a + next to Modules; click on that and you should see Module1. If
you don’t see Modules, but you do see VBAProject, you should have a + next to
VBAProject; click on that to see Modules, click on the + next to Modules to see
Module1, and double-click on Module1 to see the Module1 window. Finally, if
you don’t see Modules, and you don’t see a + next to VBA Project, then you
don’t have a module (either you never inserted it, or you deleted it). Go to the In-
sert menu, and choose “Module,” and you should be OK.
If you accidentally add more than one module, your modules will be num-
bered consecutively (Module1, Module2, Module3, . . . ). While it is not a prob-
lem to have more than one module, you should avoid confusion by keeping all
your scripts in the same module. Delete any extra modules by clicking on them
in the Project window and choosing “Delete Module” from the File menu.
Go to PowerPoint (either choose it from the Task Bar or close the Visual
Basic Editor by clicking on the in the upper right-hand corner of the screen;
on a Macintosh, choose “Close and Return to Microsoft PowerPoint” from the
File menu). Don’t worry about losing your VBA scripts when you close the edi-
tor. Your VBA scripts are part of your PowerPoint presentation. When you save
your presentation, your scripts will be saved with it. When you return to the edi-
tor, your scripts will still be there.
If you don’t have a slide, create a blank slide. Don’t worry about what kind
of slide it is or what is on it. Go to the Slide Show menu and select “Action But-
tons.” From the flyout menu, pick any button (the blank one is fine because you
can add text to it later). See Figure 4.4 to see how to add a blank action button.
You can draw the button by dragging the mouse to form the button or just
clicking where you want the button to appear on the slide. Once you let go of the
mouse you will be presented with the Actions Settings dialog box (see Figure
4.5). Choose Run Macro, and select SayHello (the name of the procedure you
just wrote) as the macro to run. Click OK.
Buttons are only active in Slide Show View, so go to Slide Show View
(choose “View Show” from the Slide Show menu or click on the Slide Show
icon in the lower left corner of the screen). Now, click on your button, and
you should get the same “Hello” message you got earlier when running your
procedure (see Figure 4.2, page 42).
Tying Your VBA Script to Any Object 45
Now go back to Edit View (also known as Normal View) by hitting the Es-
cape key on your keyboard. To finish your button, right-click (control click on a
Macintosh) on it and choose “Add Text” from the flyout menu. You can now add
text to describe what your button does. This text will show up on the button, so
users will know what they are clicking when they click your button.
Changing a Button
You might want to make three types of changes to your button: changing
the PowerPoint attributes of a button, such as size shape, or text; changing which
script a button uses (including adding a script if the button isn’t tied to one); and
changing what the script does that the button uses.
To change the attributes of a button, you would use traditional PowerPoint
features. For example, you can change the text in the button by right-clicking on
the button and choosing “Edit Text” (“Add Text” if the button doesn’t already
have any text) from the flyout menu. You can use any of the drawing tools to
change the size, shape, color, etc., of the button.
If you created your button and didn’t tie it to a script, you can right-click on
the button and choose “Action Settings” from the flyout menu. Alternatively,
you can left-click on the button to select it, go to the Slide Show menu, and
choose “Action Settings.” Once in the Action Settings dialog box (see Figure
4.5, page 45), you can choose Run Macro. If you had associated your button with
the wrong script, you can change which script the button runs in the Action Set-
tings dialog box. If you have more than one script, you can choose a different
script from the pull-down menu under Run Macro. If you don’t want your button
to run any script, click None in the Action Settings dialog box.
Check the box that is labeled “Lock project for viewing,” type a password
in the password box, and type the same password in the “Confirm password”
box. Now, whenever you want to view or edit the VBA code, you will be asked
to type this password. Don’t forget it, or you will not be able to access your own
project.
Note that in newer versions of PowerPoint (beginning with 2002), you can
set a password to access your file. If you choose to use this, beware of two
things: (1) Anyone viewing your presentation will need the password, and (2)
anyone using a version of PowerPoint earlier than 2002 will not be able to view
your presentation.
48 Getting Started with VBA
Conclusion
You now have control over navigation, you know how to lock your scripts
with a password, and you know the basics of writing VBA scripts. You are ready
to learn some more sophisticated scripts to promote interactivity.
Exercises to Try
Introduction
In Chapter 4 you learned how to access the VBA Editor and write a simple
script. In this chapter you will begin to learn a few more basic scripts, including
some scripts that allow you to get input from the user. In the process, you will
learn a little bit about variables, which are used to store information, so you can
use it when you give feedback. What good would it be to ask for the user’s name,
if you don’t use it as part of the feedback? You will get a preview of how to use
some of the same scripts to get other kinds of in put, such as answers to short-
answer questions. Finally, in this chapter you will learn some details about run-
ning your scripts and associating them with buttons, including how to associate a
button with more than one script.
Vocabulary
• Ampersand (&) • String
• Declare • Underscore
• Dim • Variable
• InputBox • Variable type
• Scope
50 Let’s Get Scripting
There are a few important things about this simple procedure. First, pay at-
tention to the space and underscore at the end of the line. The last three charac-
ters on the second line are comma, space, and underscore. Without the space, the
computer won’t recognize the underscore that follows. The underscore is a spe-
cial VBA character that tells VBA that what is on the next line is part of this line.
Therefore that entire line could have been written on one line without the
underscore:
userName = InputBox(Prompt:="Type your name", Title:="Input Name")
The underscore simply allows you to divide long lines so you don’t have to
scroll to the right to see what is on each line. Feel free to write long lines on one
line or divide them up among several lines as you see fit.
The next thing that is important about this small piece of code is that it uses
a variable: userName. Since we don’t do anything with the variable at this point,
it is not terribly interesting, but we should note a few things about variables.
Variables are places to store information. You can think of them as boxes in the
computer’s memory. Unlike algebraic variables, which represent one (or more
than one) specific, unchanging value in an equation or series of equations, com-
puter variables change values. That is, you can take something out of a box and
put something else into the box. In algebra, the equation
x = x + 1
would not make any sense. In the computer, it makes perfect sense for two reasons:
1. While the variable x can only hold one value at a time, that value can
change. At one time x might hold the value 7, and a moment later, x
might hold the value 8.
2. The equal sign (=) is not a statement of equality. It is an assignment
operator. It says, take the value on the right side and store it in the
variable named on the left side. Therefore, the above equation is not a
statement of algebraic fact; it is an action. The part on the right (x + 1)
says, find what the value of x is and add one to it; the rest (x =) says,
Variable Declarations 51
store that value in x. That is, if x was 7, it will now be 8. Using the
box analogy, it says, look in the box we call “x,” add one to what you
find there, and put the result back in the box.
In the YourName procedure, we have used the variable userName. What
we have said is: Take whatever the user types in the InputBox and put it into a
variable called userName. Later, we will want to use the name (to say, for exam-
ple, “Good job, Ella”) so we will get it out of the userName box when we are
ready.
Variable Declarations
For a variable to be useful, you often need to declare it. Although it is not
necessary to declare all variables, it is good practice to do so. Declaring a vari-
able does two things for you: It tells the computer what procedures are allowed
to know about the variable (scope), and it tells the computer what kind of infor-
mation the variable can hold (type). Declaring a variable is very easy. You do it
with the Dim statement:
Dim userName
This line tells the computer that you want a box called userName to store some
information (see Figure 5.1, page 52).
52 Let’s Get Scripting
The most important part about the Dim statement is where to put it. You
have two choices: You can put it at the beginning of your procedure (right after
the Sub statement) or at the beginning of your module (before any Sub state-
ments). If you put it any place else, it will not work. While programmers have
lots of good reasons to put Dim statements in procedures, we are scripters, so for
the purposes of this book, we will put most of our Dim statements at the begin-
ning of the module. A Dim statement at the beginning of a module means that
every procedure in the module can access that variable. That is, the scope of the
variable is the entire module.
Alternatively, if you put the Dim statement at the beginning of the proce-
dure, only that procedure can use the variable; that is, the scope of the variable is
the procedure. For the YourName procedure, it would be pretty silly to create
the userName variable so that only YourName could use it. If we did that,
when we add a second procedure (such as the DoingWell procedure to tell the
user how well he or she is doing), we won’t be able to use the name typed by the
user. That is, we would be stuck saying “Good job” instead of “Good job, Ada.”
Therefore, we want to add a Dim statement at the beginning of the module:
Variable Types 53
Dim userName
Sub YourName()
userName = InputBox(Prompt:="Type your name", _
Title:="Input Name")
End Sub
Just be sure that the Dim statement, along with all other Dim statements, is the
first thing in your module regardless of where in the module the YourName pro-
cedure is.
Variable Types
Variables are of certain types. That is, certain variables can hold certain
kinds of information. If you don’t tell the computer what kind of information the
variable is holding in advance, it will figure it out. In the YourName procedure,
the function InputBox always returns a variable of type String (a String is
text), so VBA will figure out that userName is a String. However, it is a good
idea to be explicit and tell the computer that you want userName to be of type
String. You can do this by changing the earlier Dim statement:
Dim userName As String
This Dim statement not only tells the computer that we want a variable called
userName, but it also tells it what kind of information that variable can hold (us-
ing our box analogy, it tells it the size and shape of the box). In this case, our
variable will hold a String (i.e., text) of up to 65,536 characters long.
Note that when you type a space after As, most versions of the VBA editor
will try to suggest things for you to type with a little box that pops up (see Figure
5.2).
This box contains all the things that you can type now. Boxes like this will pop
up frequently. If you know what you want to type, just ignore the box. If you’re
not sure what you want to type, scroll through the list to see the possibilities. If
you find what you want on the list, you can either type it yourself or double-click
54 Let’s Get Scripting
on it in the box. When you double-click it will appear just as if you typed it, ex-
cept that the computer will never spell it wrong.
For Dim userName As, you’ll see all the types of things that userName
can contain. There are about 300 of them, but there are just a few that you will
care about now. Common types you will use are:
Now, we are ready to put it all together with a Dim statement and two pro-
cedures:
Dim userName As String
Sub YourName()
userName = InputBox(prompt:="Type your name", _
Title:="Input Name")
End Sub
Sub DoingWell()
MsgBox("You are doing well, " & userName)
End Sub
The first procedure could be associated with a button on the first slide, and
the second procedure could be associated with a button on a later slide. The re-
sult would be that when the first button was pressed, the student would be asked
to “Type your name.” If the student types “Ada,” when the second button is
pressed, a message would pop up on the screen saying, “You are doing well,
Ada.” The & (ampersand) character used in the MsgBox procedure is for concat-
enation of strings; i.e., the two strings “You are doing well,” and whatever is
stored in the variable userName (in this case “Ada”) are joined together to
make one string, “You are doing well, Ada,” which is displayed in the box on the
screen.
Of course this is a simple example, but it is really easy to turn it into a multi-
ple-choice quiz with feedback that uses the student’s name. Figure 5.3 shows the
VBA script and slides for a short quiz. The arrows show which button should be
connected to which procedure. The Next buttons and Quit button do not use
Force the Student to Type Something 55
VBA; they use traditional hyperlinks (see Chapter 2) for Next Slide and End
Show. If you have forgotten how to tie your buttons to a procedure, look back in
Chapter 4.
To decide if the student has typed anything, we use a variable named done.
When done is True, the user has typed something. When done is False, the
user hasn’t typed anything. You might notice that we declared this variable in-
side the procedure YourName. This means that only YourName will know about
done (it would work just fine to declare done at the beginning of the module
right before or after the Dim statement for userName). done is declared as
Boolean because Boolean variables can be True or False, and we are either
done or we are not done.
We start by setting the value of done to False (because the student surely
has not typed a name before we even have asked). Next, we use a While loop
(see Chapter 8 for more about While loops). This is a method of doing some-
thing over and over again as long as we want to keep going. We know we want to
keep going if whatever comes after the word While is True. Not False is the
same thing as True, so if done is False, Not done is True, and we keep go-
ing. In English, we keep going as long as we are not done.
How do we know when we are done? That is where the If statement comes
in. We check to see what the student has typed (as stored in userName) and
compare that to "" (that is two double quotes with nothing between them, also
known as the empty string or nothing). If the student typed nothing (If
username = "" Then) then we are not done, so we set done to False (done
= False); that is, we put the value False in the variable named done. Other-
wise (Else) the student must have typed something, so we are done, and we set
What Else? A Personal Response and a Short-Answer Question 57
done to True (done = True). The Wend just says that we are at the end of our
While loop. Everything between the While and Wend will be executed over
and over again until we are done (in this case, until the student types something).
If the user types nothing, the If statement will set done to False, and loop
back up to the While statement. The While statement will see that we are not
done, so we should keep going and execute the stuff between While and Wend
again. If the user types something, the If statement will set done to True and
loop back up to the While statement. The While statement will see that we are
done and move to whatever is after the Wend (we could do something else after
the Wend, but we don’t in this example).
Two things to note:
1. Students will be forced to type something, but that something could
be anything: a single space, a dirty word, a period, etc.
2. Students will only be forced to type something if they click on the
button associated with this script.
In later chapters, you’ll learn how to check what was typed to make sure it
is OK, as well as how to force the student to click on the button (don’t worry; it
doesn’t involve physical force or shock therapy).
done = False
While Not done
userName = InputBox(prompt:="Type your name", _
Title:="Input Name")
If userName = "" Then
done = False
ElseIf userName = "Emily" Then
MsgBox("Finish your homework before doing this.")
done = False
Else
done = True
End If
Wend
End Sub
58 Let’s Get Scripting
After we ask the question about the student typing nothing, we ask one
more question. So first, we check to see if userName is nothing. If it isn’t, we
ask if userName is “Emily.” If userName isn’t nothing, and it isn’t Emily, then
we look at what comes after Else. If userName is “Emily,” we have two things
to do: put up a message telling Emily to do her homework, and set done to
False. Because done is False (just like it would be if the student typed noth-
ing), we’ll ask for the name again.
This could be expanded to ask as many questions as you want by adding
more ElseIf questions. Each one could check for a different name (or an unac-
ceptable answer, like profanity) and respond appropriately. Note that ElseIf
does not have a space between “Else” and “If” while End If does have a space
between “End” and “If.”
Using the exact same structure, we can change this from asking for a stu-
dent’s name to asking for the answer to a question. The main structure of the
VBA looks like this:
Sub Question()
Dim done As Boolean
done = False
While Not done
answer = InputBox(prompt:="What color is the sky?", _
Title:="Question")
If answer = "" Then
done = False
ElseIf answer = "blue" Then
MsgBox("Good job.")
done = True
Else
MsgBox("Try Again.")
done = False
End If
Wend
End Sub
You should notice that this is almost identical to YourName, with the following
exceptions:
• We changed the name of the procedure; you can name procedures
anything you want as long as they make sense to you.
• We changed the name of the variable; you can name variables any-
thing you want as long as they make sense to you.
• We changed the text in the InputBox; as a scripter, you always
should look for text between quotes that you can change.
• We changed the text in the ElseIf line to check to compare what
was typed to the right answer; remember, as a scripter, you should be
looking to change the text for the question and the text for the an-
swer to whatever you want.
Calling a Procedure from Another Procedure 59
Generally, we won’t use method 1. Although it will work for some of the
simple scripts we have written so far, it will not work for most of our scripts be-
cause we will design our scripts to be run in Slide Show View. When we choose
“Run Sub/UserForm,” we are not in Slide Show View.
Most of the time, we will use method 2, associate the procedure with a but-
ton. We did this at the beginning of Chapter 4. Remember that procedures aren’t
magic; they have to be told to run. The best way to tell them to run is to associate
them with a button and to click on that button in Slide Show View.
Sometimes we will want to use method 3. In this method we write one
script that includes the names of other scripts in it. Our button will be associated
with the first script, but when that script is run, the other scripts will run as well.
The next section describes this in more detail.
Sub DoingWell()
MsgBox("You are doing well, " & userName)
End Sub
You could associate a button with each of these procedures, so the users
click on the first button to type their names and (probably at some later point)
click on the other button to be told how well they are doing. What if we want to
praise them right away, to encourage them right after they have typed a name?
We could write another procedure that calls the two procedures above:
Sub YourNameWithPraise()
YourName
DoingWell
End Sub
Conclusion
You now have learned a few basic scripts to interact with your students.
You can get input and use it in feedback, either to include a student’s name in the
feedback or to judge a short-answer question. In the next chapter you will ex-
pand your bag of VBA tricks, including ways to manipulate your PowerPoint
slides, such as moving from slide to slide and hiding objects on your slides.
Exercises to Try
Ä If you completed the “Exercise to Try” in Chapter 4, edit your
presentation to change the RightAnswer and WrongAnswer
scripts to include the student’s name. Be sure to add a button on
the first slide, to ask for the student’s name (using the YourName
procedure in this chapter).
Ä Add another slide to your quiz with a short-answer question. Put
a single button on the slide that pops up the question. Use a dif-
ferent question than the one in this chapter. Don’t worry if you
can’t figure this out. Chapter 7 includes detailed instructions on
how to do this.
6
A Scripting Bag of Tricks
Introduction
In Chapter 5 you began to expand your single trick (the MsgBox) into a
small bag of tricks. On the way you learned some important lessons about vari-
ables, loops, and If statements. With this, you have the power to do some inter-
esting things to your PowerPoint projects. You can create an interactive
multimedia extravaganza as long as you only want it to be a little interactive. In
this chapter, you’ll expand your bag of tricks to include several interactive fea-
tures including navigation (i.e., moving around from slide to slide); hiding and
showing PowerPoint objects; and changing text, font, size, and style in objects.
You’ll finish off the chapter with an example that ties some of the tricks to-
gether: You’ll create a simple mystery with a clue sheet on which users can keep
track of clues.
Vocabulary
• Comment • Placeholder
• Constant • Property
• Initialize • RGB
• Navigation • TextRange
• With Block
64 A Scripting Bag of Tricks
Comments
Starting in this chapter, our examples are going to get a little more compli-
cated. That makes this a good time to talk about comments. So far, any explana-
tion of the VBA code has been placed in the text, but it might be helpful to have
some explanation built right into the code. This will be useful for me to explain
things to you, and it will be useful for you to explain things to yourself. Com-
ments are good at the beginning of procedures, as a brief note at the end of a line,
and as a note inside a procedure. In addition, comments are helpful to point out
obvious things because what is obvious to me might not be obvious to you, and
what is obvious to you now might not make as much sense when you look at it
later. And comments are helpful to point out things that are not obvious. A line
like
If answer = "" Then
obviously checks to see if the variable answer contains nothing, but it might be
helpful to put a comment, such as “The user didn’t type anything.”
If answer = "" Then 'The user didn’t type anything.
The comment starts with a single quote. This tells the computer to ignore every-
thing else on the line. That is, comments are for people looking at VBA code, not
for computers running VBA code; the computer ignores the comments. As in
this example, the comment can appear at the end of a line, or it can appear on a
line by itself or even on several lines each starting with a single quote:
'This procedure is our very first procedure.
'It puts a message on the user’s screen that says "Hello."
Sub SayHello()
MsgBox("Hello") 'This is the line that puts up the message.
End Sub
If you type this example into your VBA Editor, you will notice that the
comments turn green. That will help you distinguish VBA code for the computer
from comments for you.
The next section discusses how VBA can be used to move from one slide to
another. This is an excellent place for a comment. The VBA command will tell
you that you are moving to slide 3, for example, but it won’t tell you why. If, for
example, slide 3 is your menu, a comment that says “Returning to the main
menu” will help you understand what your script is supposed to do.
you hadn’t seen this before, you learned about it in Chapter 2. In fact, almost
anywhere you can go with VBA you can go with traditional PowerPoint
hyperlinks. So why would you want to complicate your life by doing something
with VBA that you already can do without it? This is a trick question. While you
can link to the same places without VBA, your hyperlinks only work when you
click a button or text, and linking will be the only thing that button or text does.
With VBA, you can link and do something else, or you can link to different
places depending upon the answer to a question (using something like what we
did in Chapter 5 with the YourName procedure or the Question procedure).
At the end of Chapter 5 you saw the procedure YourNameWithPraise.
This procedure did two things: It asked for the student’s name and it said, “You
are doing well.” Let’s start with that and make one small addition:
Sub YourNameWithPraise()
YourName
DoingWell
ActivePresentation.SlideShowWindow.View.Next
End Sub
The line that we added moves to the next slide. Don’t worry how it does it; just
remember that any time you want to use VBA to move to the next slide, you can
insert that line into your procedure.
Imagine a title slide of your presentation. The only button on the slide
would be associated with this procedure (of course, you would need the
YourName and DoingWell procedures in your module, but only
YourNameWithPraise would be tied directly to a button). When the user
clicks on the button, YourName is called (the user is asked to type a name),
DoingWell is called (the user is told by name, “You are doing well”) and the
presentation automatically begins by moving to the next slide.
Of course, you don’t always want to go to the next slide. To move around
within your presentation, you can use any of the following:
With the first statement, you can go to any slide in the presentation. Simply re-
place “3” with the number of any other slide. The only difficulty is that if you
change the order of your slides, insert a new slide, or delete a slide, you will have
to change the number. In Chapter 8, we will discuss naming slides. You will be
able to set the names for your slides and use the name to go to a particular slide.
The ability to move around can be very powerful, particularly when the
slide to which you want to go is based on something the user types or does. The
next section reveals some secrets of MsgBox and ends with an example that
moves to a particular slide based on which button is pressed in the MsgBox.
Button(s) Constant
OK vbOK
OK, Cancel vbOKCancel
Abort, Retry, Ignore vbAbortRetryIgnore
Yes, No, Cancel vbYesNoCancel
Yes, No vbYesNo
Retry, Cancel vbRetryCancel
We can now use a MsgBox to ask a simple question. We don’t have a lot of
choices for the answers (just the limited choices above), but at least we can ask a
yes/no question with a MsgBox. For anything more complicated, just use action
buttons on a slide and skip the MsgBox.
To put more buttons in a MsgBox, we need to do two things: add a second
argument to the MsgBox command (that’s where the secret word comes in) and
store the answer in a variable. Because the user can press one of two or three but-
tons, we need a way to keep track of which button was pressed. For example:
whichButton = MsgBox("Do you like chocolate?", vbYesNo)
The variable whichButton will store information about which button was
pressed, and the second parameter to MsgBox (after the message that is to appear
The Secrets of the MsgBox 67
and the comma) is the constant that tells MsgBox which buttons to use. Figure
6.1 shows the MsgBox.
The secret words are called constants because they represent constant val-
ues (unlike variables, which can change value). In this case, the constants are
mnemonics for numbers. For example, vbYesNo is really the number 4. Wher-
ever you see the constant vbYesNo, you could type 4 instead. However, it might
be easier to remember that vbYesNo means “I want Yes and No buttons” than
remembering what 4 means in a MsgBox command. You can make your own
constants, but we’ll just use the ones that come with VBA; these usually start
with the letters vb (for Visual Basic) or mso (for Microsoft Office), so if you
ever see something that starts with vb or mso, it is probably a constant.
VBA comes with hundreds of constants that can be used with different
commands, and it comes with a few more for the MsgBox command. The most
important ones are values returned by MsgBox depending on which button was
pressed. The following are the possible values: vbOK, vbCancel, vbAbort,
vbRetry, vbIgnore, vbYes, and vbNo. For example, if the user clicks the Yes
button, MsgBox returns vbYes. We might want to do something based on the
button pressed. For example:
'Ask if you like chocolate. Give an appropriate response.
Sub Chocolate()
Dim chocolateAnswer
'Ask if you are sure you want to quit. If the answer is Yes,
'exit the presentation. If the answer is No, go to the next slide.
Sub QuitOK()
'result is a variable to keep track of which button is clicked.
Dim result
'MsgBox returns (will set the variable result to) vbYes if the
'Yes button is clicked and vbNo if the No button is clicked.
result = MsgBox("Are you sure you want to quit", vbYesNo)
If result = vbYes Then 'Was the Yes button clicked?
ActivePresentation.SlideShowWindow.View.Exit
Else 'Since Yes wasn’t clicked, it must be No
ActivePresentation.SlideShowWindow.View.Next
End If
End Sub
With the additional power of MsgBox, you have another tool to do something
based on the answers to simple questions. By combining this with navigational com-
mands from the previous section, you can let the user go anywhere in your presenta-
tion based on the answers to questions. But moving from slide to slide isn’t the only
response. You might want to stay on the same slide and have something magical hap-
pen. In the next section, you will learn how to make objects appear and disappear.
Change False to True, and you show the object once again:
ActivePresentation.Slides(2).Shapes(5).Visible = True
For example, you might want a star to appear on a slide when a user gets the
correct answer. To do this, create the star where you want it (using regular
PowerPoint drawing tools). Even add text, such as “Good job!” See “Manipulat-
ing Text in Objects” below for more about changing the text on the fly to include
the current score or the user’s name. Before this can work effectively, we’ll need
to set up the presentation before the user gets to the slide with the star. This will
require us to initialize the presentation.
Let’s Get Started: Initializing Your Presentation 69
You could add something to this procedure to move to the next slide, or you
can do all your initializing from this procedure and have another procedure take
care of other stuff. So let’s add a GetStarted procedure to do the other stuff as
well as call the procedure Initialize.
Sub GetStarted()
Initialize 'Hide the stars
YourName 'Ask for the name
ActivePresentation.SlideShowWindow.View.Next 'Go to the next slide
End Sub
This procedure will be linked to the button on the title slide. As the comments in-
dicate, it will use the Initialize procedure to hide the stars, it will use the
YourName procedure to ask for a name, and it will use
ActivePresentation.SlideShowWindow.View.Next to go to the next
slide. As always, because this procedure calls the YourName procedure and the
Initialize procedure, these procedures must be included in your module
along with the declaration (Dim statement) for the userName variable.
70 A Scripting Bag of Tricks
As you keep track of more things, you will set up more things in the
Initialize procedure. This will include more objects that might be hidden or
shown and variables, like ones to store the number of correct and incorrect an-
swers that need to be given initial values. You’ll see more about this in Chapter 7
when we start keeping score.
Finally, tying this all together, slides 2 and 3 will need buttons to show the
stars. These buttons might be the right answer buttons on those slides. For exam-
ple, the right answer on slide 2 might be linked to
Sub RightAnswerTwo
ActivePresentation.Slides(2).Shapes(4).Visible = True
End Sub
In the upper left corner of the dialog box, you will see the objects listed by
type and number. You can see that the text object is shape 1, the rectangle is
shape 2, and the action button is shape 3. If you have lots of objects of the same
type, you can click on the type and number of an object and the object will be
highlighted on the right.
Once you have figured out the number of the object you want, you can close
the dialog box with or without setting any animation.
For PowerPoint 2002, Custom Animation does not list all the objects on the
slide, but it will list the objects that are animated. Therefore, if you want to find
out an object’s number, click on the object to select it, choose “Custom Anima-
tion” from the Slide Show menu, and add an animation effect (see Figure 6.4).
Just as in earlier versions of PowerPoint, the number that appears after the object
type is the object’s number. In this case, the rectangle was selected, and it is ob-
ject number 2 because the animation list shows “Rectangle 2.” Note that the
number 1 on the slide and in the animation list refers to the animation order, not
the object number. After determining the object’s number, don’t forget to re-
move the animation effect by clicking on the “Remove” button in the “Custom
Animation” window.
" "
These names do not change unless you change them. If you delete Text Box
4, Rectangle 5 and AutoShape 6 will keep the same name, and nothing will have
a name with 4 in it. The number added to new names keeps going up even when
you delete shapes. Thus, if you add the above shapes and then delete them and
then insert a picture from clip art, the picture will be named Picture 7 even
though no objects include 4, 5, and 6 in their names.
In order to use the name of an object, use it in quotes in the same place you
would use the object number. Thus, to hide a shape named Text Box 4 on slide
number 5, you could use the following line:
ActivePresentation.Slides(5).Shapes("Text Box 4").Visible = False
So, for example, if you want to hide shape number 7 on the current slide, you
would use this line:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(7).Visible = False
Adding PowerPoint Objects 75
where NUM is replaced by the number of the slide. So, for example, if you want to
hide shape number 7 on slide number 2, you would use this line:
ActivePresentation.Slides(2).Shapes(7).Visible = False
Any expression throughout this book that uses a statement to affect the cur-
rent slide can be changed to use a statement for another slide, and any expression
that uses a statement to affect another slide can be changed to use a statement for
the current slide.
Set myShape = _
ActivePresentation.SlideShowWindow.View.Slide.Shapes. _
AddShape(Type:=msoShapeRectangle, Left:=100, Top:=100, _
Width:=200, Height:=200)
myShape.Fill.ForeColor.RGB = vbRed
myShape.TextFrame.TextRange.Text = "Hello"
End Sub
76 A Scripting Bag of Tricks
We are going to create a shape, so we create a variable to hold that shape. That
way, once the shape is created, we can refer to it later in the procedure. Next we
create the shape:
Set myShape = _
ActivePresentation.SlideShowWindow.View.Slide.Shapes. _
AddShape(Type:=msoShapeRectangle, Left:=100, Top:=100, _
Width:=200, Height:=200)
Try replacing msoShapeRectangle with some of the other shapes from this
list.
Finally, we set some properties of the shape. Since the shape is stored in the
variable myShape, we can use myShape to manipulate some of the shape’s
properties:
myShape.Fill.ForeColor.RGB = vbRed
This line takes the shape we just created and stored in the variable myShape and
adjusts its color. This looks complicated, but you just have to remember that if
you want to change the color of a shape, you need to adjust the
.Fill.ForeColor.RGB. After the equal sign is the color we want. There are
many ways to specify the exact color, but you can use the following basic colors:
vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, and
vbWhite.
Shapes can also have words in them. If you want to set the text in the shape
to “Hello,” use the following line:
myShape.TextFrame.TextRange.Text = "Hello"
This is simply a long way of saying that the text in this shape should be set to
“Hello.”
Adding objects can be useful, especially if you want the user to make sig-
nificant changes to the presentation. In the example in Chapter 10, the user adds
slides to the presentation. These slides become part of the presentation, and there
are an undetermined number of them (every user that goes through the presenta-
tion can add slides to it). In most cases, however, you will have a few shapes that
you have determined in advance. Rather than creating those shapes in VBA, you
would do better to create them in PowerPoint and hide and show them with
VBA. This will prevent your presentation from getting cluttered with extra
shapes when a user hits a button too many times and adds several extra shapes.
changes the text of the third shape of the current slide to “Hello.”
Now, we can put this together with YourName and Initialize to put the
user’s name in the text box:
Dim userName
done = False
While Not done
userName = InputBox(prompt:="Type your name", _
Title:="Input Name")
If userName = "" Then
done = False
Else
done = True
End If
Wend
End Sub
'Link this to the button that contains the right answer on each slide.
'Be sure you have used your drawing tools to create the 4th shape
'on each slide.
'Note that this RightAnswer does not automatically go to the next
'slide.
Sub RightAnswer
ActivePresentation.SlideShowWindow.View.Slide.Shapes(4) _
.TextFrame.TextRange.Text = "Good job, " & userName
ActivePresentation.SlideShowWindow.View.Slide.Shapes(4).Visible = True
End Sub
object, we put together some text with the user’s name, just like we did with a
MsgBox in our earlier DoingWell procedures.
Of course, you can do the same thing with a shape that you use VBA to cre-
ate, but you can figure that out for yourself.
With Blocks
Before changing the text, we should learn a simple VBA trick to save you
from typing long expressions over and over again. You might have noticed that
to get to the text for a shape, you have to type something very long, such as
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3).TextFrame _
.TextRange.Text
This refers to the text in the third shape in the current slide (it’s interesting how I
can say it in English in less space than I can say it in VBA). To save typing, we
can use a With block. For example, if we want to do several things to the third
shape on the current slide, we can do the following:
With ActivePresentation.SlideShowWindow.View.Slide.Shapes(3)
.TextFrame.TextRange.Text = "Hello"
.Fill.ForeColor.RGB = vbRed
.Visible = True
End With
The With block (starting with the first line that begins with With and ending
with the line that ends with End With) simply assumes that anything starting
with a dot really includes all the stuff on the With line. In English, it is saying, “I
want to do the following things to the third shape on the current slide: change the
text to ‘Hello’, change the background color to red, and make the shape visible.”
80 A Scripting Bag of Tricks
Adding Text
Now, suppose you want to add something to the text in your shape, rather
than replace the text. Remember the ampersand (&). This is used to join two
pieces of text together. We used it when we wanted to display text in a MsgBox
that included “You are doing well” and the user’s name. We can use it here to
join what is already in the text box with some additional text. Once we join to-
gether the text we need to stick the joined together text into the .Text of the
shape.
Sub AddHello()
With ActivePresentation.SlideShowWindow.View.Slide _
.Shapes("Rectangle 3")
.TextFrame.TextRange.Text = _
.TextFrame.TextRange.Text & Chr$(13) & "Hello Mother"
End With
End Sub
The With line (including the next line that is really part of that line due to the un-
derscore) tells the computer that we are going to do something with the shape
named “Rectangle 3” on the current slide. If the current slide is a Bulleted List
slide, “Rectangle 3” refers to the bulleted list area (the main area for text).
.TextFrame.TextRange.Text = _
tells the computer that we are going to put something into the text area of that
slide. After the equal sign, the next line
.TextFrame.TextRange.Text & Chr$(13) & "Hello Mother"
tells the computer what we are going to put into the text area. We are going to
• start with what is already there ( .TextFrame.TextRange.Text );
• add to that a special character, Chr$(13), which is the New Para-
graph symbol (just like hitting “Enter” or “Return” if you were typ-
ing the text into the text area yourself); and
• add the text “Hello Mother”.
This will have the effect of taking what was already in the bulleted list and add-
ing a new line with the words “Hello Mother.” Remember, you can do anything
with the text that you want. We added “Hello Mother” as a simple example. You
could have added the user’s name. For example, you might write an interactive
story with your students in which the student types a name at the beginning of
the story, and the name is used during the story by replacing or modifying the
text in one of the slides:
Manipulating Text in Objects 81
Sub BrickPig()
With ActivePresentation.Slides(7).Shapes("Rectangle 3")
.TextFrame.TextRange.Text = .TextFrame.TextRange.Text & _
"And then the third pig, " & userName & _
", built a house of bricks. The brick house " & _
"was very strong."
End With
End Sub
This takes the shape named “Rectangle 3” on the seventh slide and adds text to it
that includes the user’s name (assuming you have used the YourName procedure
at some previous point to get the user’s name). If “Rectangle 3” is a Placeholder
(see below for information about Placeholders), be sure it has something in it
when you try to run this code, or your text will not show up until after you exit
Slide Show View.
As another example, imagine that you are having a class discussion, and
you want to record the students’ comments in your PowerPoint presentation.
Perhaps you are discussing the signs of spring, and you want the class to tell you
signs of spring related to plants and animals. Without technology, you would
write the information on the blackboard. However, this is awkward if you are us-
ing PowerPoint as part of the discussion; it is awkward to run from the computer
to the blackboard, and it is awkward to flip the lights off and on so students can
see the screen and the blackboard alternately. Instead, use this simple code to put
the text right into the PowerPoint presentation:
Sub AddPlants()
Dim newstuff As String
Sub AddAnimals()
Dim newstuff As String
This code works on a slide with two text boxes that you add as the second
and third shapes on the slide, and it works with a 2-Column Text slide. Just be-
ware that if you add text to an empty Placeholder (that’s one of those text boxes
that says “Click to add text” or “Click to add title” before you put anything in it,
82 A Scripting Bag of Tricks
i.e., your title, left column, and right column in the 2-Column Text slide), your
text will not show up until you exit the slideshow. To avoid this problem, either
use a Title Only slide and draw your own text boxes or type a space in the text
area so the Placeholder is not empty.
The code works with the slide shown in Figure 6.6. This figure shows the
slide before and after typing some text. In this case, you would have pressed the
Plant button (which is tied to the AddPlant procedure) twice and the Animal
button (which is tied to the AddAnimal procedure) once, having been prompted
by an InputBox each time to name a sign of spring. The If statement in each
procedure (along with the corresponding End If) can be left off, but it provides
you with an escape if you accidentally hit the wrong button: Simply click OK
without typing anything. The If statement asks if you have typed something
(i.e., the text you typed is not the empty string), and it only adds the text to the
slide if the answer is yes.
Of course the entire example could be simplified with one procedure, one text
box, and one button if you don’t want to organize student responses into two columns.
It can also be complicated by adding more similar procedures, more text boxes, and
more buttons if you want to divide student responses into more than two areas.
Almost identical code can be used to change the second paragraph of the third
shape on the current slide to blue:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
TextFrame.TextRange.Paragraphs(2).Font.Color.RGB = vbBlue
Note that paragraphs include the New Paragraph symbol, Chr$(13), as part of
the paragraph. Thus, you must be careful when changing the text of a paragraph
to be sure that each paragraph ends with Chr$(13). See the Mystery Example
later in this chapter for an example of this. With another small change, the sec-
ond word becomes blue:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
TextFrame.TextRange.Words(2).Font.Color.RGB = vbBlue
Note that VBA counts punctuation marks as words. For example, the text
“Hello, my name is David” has six words (by VBA’s count; who said computers
were smart?), with the comma being the second word. With another small
change, the second character becomes blue:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
TextFrame.TextRange.Characters(2).Font.Color.RGB = vbBlue
Finally, any of these statements can be altered slightly to include a range of para-
graphs, words, or characters. Simply include a second number after the “2” to
tell how many paragraphs, words, or characters you want to affect. For example,
if you want to make seven characters blue, starting with the second one, you
would use the following:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
TextFrame.TextRange.Characters(2,7).Font.Color.RGB = vbBlue
If the text is “Hello, mother,” then the characters “ello, m” would turn blue (the
comma and space count as the fifth and sixth characters).
This is the same as if you had selected the text and clicked on the Bold button in
the toolbar.
84 A Scripting Bag of Tricks
You can also set the Size of the text to a particular point size. For example, if
you wanted to change the text to a 12-point font size, you could use the following:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
TextFrame.TextRange.Font.Size = 12
You can change the Name of the font, but you should beware; if this presen-
tation is running on a variety of computers, you should stay away from fonts that
are not standard because your font will only show up properly if the computer on
which the presentation is running has the font. To change the font to Helvetica,
you can use the following example:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
TextFrame.TextRange.Font.Name = "Helvetica"
Finally, you can change the color in a number of ways. You have already
seen that you can choose from some VBA constant colors: vbBlack, vbRed,
vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, and vbWhite. You can
also set colors by using an RGB value. RGB stands for Red Green Blue. You
will specify a color by indicating how much red, how much green, and how
much blue the color contains. For example, to make the text red, you could use
the following:
ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
TextFrame.TextRange.Font.Color.RGB = RGB(255,0,0)
This means that you want lots of red, no green, and no blue (the numbers range
from 0 to 255). You can experiment with the numbers to find just the right shade
you want. For example, RGB(150,0,75) gives a lovely shade of purple.
This will cut the third and fourth words in the third shape of the current slide (re-
member the “3,2” means start with the third word and do this for two words).
Next it will find the fourth and fifth words (counting words without the text that
was just cut) and replace them with what you cut. So if the text was “one two
Manipulating Text: The Mystery Example 85
three four five six seven eight nine ten,” the Cut will change the text to “one two
five six seven eight nine ten,” and the Paste will change it to “one two five three
four eight nine ten.” Change the Cut to Delete to get rid of the text without the
ability to paste it, and change it to Copy to copy the text without removing it
from the original location.
You can also find out how long (i.e., how many characters) a TextRange is
with Length:
MsgBox (ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
.TextFrame.TextRange.Length)
This will pop up a MsgBox with the number of characters in the third shape of the
current slide.
Finally, you might want to know how many words or paragraphs are in a
TextRange. You can use Count to find this out:
MsgBox (ActivePresentation.SlideShowWindow.View.Slide.Shapes(3). _
.TextFrame.TextRange.Paragraphs.Count)
This will pop up a MsgBox with the number of paragraphs (change Paragraphs
to Words to get the number of words).
This uses a With block because both paragraphs are part of the TextRange of
the TextFrame of the second shape on the fifth slide. Note that we add
Chr$(13), the new paragraph symbol, to the end of the first paragraph. Without
it, the paragraphs would run together.
We also want to hide the picture of the apple pie (which is the seventh shape
on the fifth slide) because it will only be shown when the user gets the right an-
swer:
ActivePresentation.Slides(5).Shapes(7).Visible = False
If you add more clues, update the GetStarted procedure to refer to what-
ever slide number is the last slide. That is, change the “5” to another number in
both lines referring to the slide.
Figure 6.8. The Mystery Presentation VBA Code
88 A Scripting Bag of Tricks
changes the first paragraph (the one that includes the eye color clue) to whatever
the user typed. The If statement then checks to see if what was typed was
“blue”:
If userClue = "blue" Then
If it is, it changes the color of the fourth word (which would be the word “blue”)
to blue:
.Paragraphs(1).Words(4).Font.Color.RGB = vbBlue
The ElseIf part checks to see if the user typed green and changes the color of
the text to green.
Guess uses an InputBox to ask for the user’s guess. The part that checks
for the correct answer is a series of If, ElseIf, ElseIf, ElseIf, and Else
statements. The If section is for the right answer. It shows the picture of the ap-
ple pie (because DeeDee wanted the apple to make pie):
ActivePresentation.Slides(5).Shapes(7).Visible = True
And when the user clicks OK on the MsgBox, it jumps back to the beginning:
ActivePresentation.SlideShowWindow.View.GotoSlide (1)
The two ElseIf clauses each bring up a MsgBox with specific feedback
about what was wrong, and the Else clause (if the user typed anything besides
“DeeDee,” “BeeBee,” or “CeeCee”) brings up a MsgBox that gives the generic
feedback “Try again.”
To create your own mystery, simply change text on the mystery and clue
slides, change the text in the VBA code that refers specifically to eye color and hair
color (in case your clues are about something else), change the text on the eye color
and hair color buttons, and change the If block in the Guess procedure to give ap-
propriate feedback for the possible guesses in your mystery. You might also want to
Exercises to Try 89
change the picture of the apple pie to something else. If you add more clues, simply
copy one of the clue slides, change the text, and change Slides(5) to Slides(6)
or Slides(7) or whatever number the last slide is. Finally, you might have to ad-
just some of the shape numbers. For example, when you create this yourself, your
picture (replacing the apple pie picture) might not be Shapes(7).
Conclusion
In this chapter you learned some powerful VBA tricks that allow you to
move around in your presentation and manipulate the objects on your slides.
You now have the power to hide and show objects and manipulate the text in
your objects. This allows you to expand feedback from a simple MsgBox to
something that changes the text in the slides. For simple feedback, a MsgBox is
fine, but to incorporate what your students have to say into the fabric of the pre-
sentation, nothing beats changing the text on your slides. The discussion ended
with a creative mystery example that shows how this technology can go beyond
simple tutorials and quizzes. In the next chapter you will see how to build quiz-
zes of varying complexity with different types of questions and different ways of
tracking and reporting scores.
Exercises to Try
Ä Take the mystery example at the end of this chapter and rewrite
it to include your own mystery. Start by changing the text of the
mystery and updating the questions. Next, change the clue sheet
to match your clues and change the apple pie picture to match
your mystery.
Ä If you are feeling adventurous, try expanding the mystery beyond
two clues by adding more clue slides and more paragraphs on the
clue sheet.
7
Quizzes and Tests
Introduction
In Chapter 6 you learned a number of powerful tricks. In fact, you now have
most of the basic skills you need to create a wide range of interactive projects. If
you fancy yourself a programmer, you can stop here and figure everything else
out for yourself. However, since this book is for scripters, we will continue with
a few more tricks and many more examples.
In this chapter you will learn about different ways to create quizzes and
tests with VBA. We’ll start with simple multiple-choice tests, add scripts to keep
score, give options for tests that only allow one try to get the right answer or al-
low multiple tries, add short-answer questions, add a script that creates a new
slide with complete test results suitable for printing, and add a multiple-part tu-
torial that won’t let your students take the test until they have completed the en-
tire tutorial. By the time you finish this chapter, you will have the skills
necessary to create tests in a variety of different ways.
Vocabulary
• ActivePresentation.Slides.Add • numIncorrect
• LCase • Round
• numCorrect • Trim
92 Quizzes and Tests
Sub WrongAnswer()
MsgBox ("Try to do better.")
End Sub
With a little help from Chapter 5, you can include the user’s name in your
feedback:
Dim userName
Sub YourName()
userName = InputBox(prompt:="What is your name?")
End Sub
Sub RightAnswer()
MsgBox ("Good job, " & userName)
End Sub
Sub WrongAnswer()
MsgBox ("Try to do better, " & userName)
End Sub
Next, add a little bit of help from Chapter 6 to automatically jump to the
next question after the right answer is chosen:
Sub RightAnswer()
MsgBox ("Good job, " & userName)
ActivePresentation.SlideShowWindow.View.Next
End Sub
Keeping Score
If you create a test with the above procedures attached to the right and
wrong answers, you don’t have to change your slides or buttons at all to add
scorekeeping; you just need some small additions to your VBA. Figure 7.1
shows the slides for a simple test along with the VBA code that gives feedback
and keeps score. The arrows show which buttons are tied to which procedures.
Although this example only has two questions, and each question has two
possible answers, this easily can be expanded to include more questions and
more possible answers. In fact, the VBA script remains exactly the same. You
simply add more slides and tie the buttons to the RightAnswer and
WrongAnswer procedures.
94 Quizzes and Tests
If you want to report the number of right answers and the number of wrong
answers but not the total, you can use this:
MsgBox("You got " & numCorrect & " right and " _
numIncorrect & " wrong, " & userName)
If you would like to report a percentage score, you can use this:
MsgBox ("You got " & _
100 * numCorrect / (numIncorrect + numCorrect) & "%, " & userName)
Finally, if you want that percentage score rounded off, you can use this:
MsgBox ("You got " & _
Round(100 * numCorrect / (numIncorrect + numCorrect), 0) & _
"%, " & userName)
Note that the 0 represents how many places after the decimal point to show, so if
you like the result “33%,” use 0; if you like the result “33.3%,” use 1; etc.
This is just the tip of the iceberg with what you can do with tests. Variables
can be used to keep track of any information you want; for example, you could
allow students to try answering a question again but only count the first try.
Try Again: Answer Until It’s Right 95
More complicated scripts can be used to judge other kinds of test questions;
short-answer questions are a small step away. With VBA, the possibilities are
endless.
Sub GetStarted()
Initialize
YourName
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Initialize()
numCorrect = 0
numIncorrect = 0
qAnswered = False 'ADDED
End Sub
Sub YourName()
userName = InputBox(prompt:="Type your name")
End Sub
96 Quizzes and Tests
Sub RightAnswer()
If qAnswered = False Then 'ADDED
numCorrect = numCorrect + 1
End If 'ADDED
qAnswered = False 'ADDED
DoingWell
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub DoingWell()
MsgBox ("You are doing well, " & userName)
End Sub
Sub WrongAnswer()
If qAnswered = False Then 'ADDED
numIncorrect = numIncorrect + 1
End If 'ADDED
qAnswered = True 'ADDED
DoingPoorly
'DELETED ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub DoingPoorly()
MsgBox ("Try to do better next time, " & userName)
End Sub
Sub Feedback()
MsgBox ("You got " & numCorrect & " out of " _
& numCorrect + numIncorrect & ", " & userName)
End Sub
The other change to your slides will be to tie your right and wrong answer
buttons to new procedures. We will need a new procedure for each question’s
right and wrong answers, rather than one procedure for all right answers and one
for all wrong answers. These specialized procedures will check the variables
(q1Answered, q2Answered, . . . ) to see if the questions have been answered
and will update the variables and the score appropriately.
Here is the complete VBA code for this example. Comments have been
used to indicate changes from the previous example:
Dim numCorrect As Integer
Dim numIncorrect As Integer
Dim userName As String
Dim q1Answered As Boolean 'ADDED to replace qAnswered
Dim q2Answered As Boolean 'ADDED to replace qAnswered
Sub GetStarted()
Initialize
YourName
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Initialize()
numCorrect = 0
numIncorrect = 0
q1Answered = False 'ADDED to replace qAnswered
q2Answered = False 'ADDED to replace qAnswered
End Sub
98 Quizzes and Tests
Sub YourName()
userName = InputBox(prompt:="Type your name")
End Sub
Sub DoingWell()
MsgBox ("You are doing well, " & userName)
End Sub
Sub DoingPoorly()
MsgBox ("Try to do better next time, " & userName)
End Sub
Sub Feedback()
MsgBox ("You got " & numCorrect & " out of " _
& numCorrect + numIncorrect & ", " & userName)
End Sub
The most significant additions are the new variables q1Answered and
q2Answered and the special right and wrong answer procedures for each ques-
tion. The variables keep track of which questions have already been answered.
q1Answered is True if question 1 has been answered, and it is False if ques-
tion 1 has not been answered. q2Answered is True if question 2 has been an-
swered, and it is False if question 2 has not been answered. If you have more
than two questions, you need a q3Answered, q4Answered, etc.; that is, you
Short-Answer Quiz Questions 99
need one variable for each question. These variables are declared at the begin-
ning with the Dim statements:
Dim q1Answered As Boolean
Dim q2Answered As Boolean
Then, in Initialize they are initialized (set to False because none of the
questions have been answered yet):
q1Answered = False
q2Answered = False
Remember that if you have more questions, you need to repeat both of these sets
of statements for each additional variable.
Next, we need our specialized RightAnswer and WrongAnswer proce-
dures. RightAnswer1 is tied to the right answer button for question 1.
WrongAnswer1 is tied to the wrong answer button(s) for question 1.
RightAnswer2 and WrongAnswer2 are for question 2. And, if we had more
questions, RightAnswer3 and WrongAnswer3 would be for question 3;
RightAnswer4 and WrongAnswer4 would be for question 4; etc.
These procedures simply check the appropriate variable to see if the ques-
tion has been answered. If it hasn’t (If q1Answered = False Then), we up-
date the score (numCorrect = numCorrect + 1 or numIncorrect =
numIncorrect + 1). Regardless of whether or not it has been answered be-
fore, we set the variable to True (e.g., q1Answered = True for question 1) and
give the appropriate feedback (calling DoingWell or DoingPoorly).
This procedure uses the variable answer to store the answer typed by the
student. Because only this procedure needs to know about it, it can be declared
inside the procedure (Dim answer). Next, we use InputBox, just like in the
YourName procedure, to ask the student to type the answer, which is stored in
the variable answer.
In our multiple-choice questions, buttons were tied to our RightAnswer
and WrongAnswer procedures. With a short-answer question, we don’t have
buttons to call these procedures, so we use an If statement. If the answer is right,
call the appropriate RightAnswer procedure; if the answer is wrong, call the
appropriate WrongAnswer procedure.
The last thing you need is a way for the question to be asked. Figure 7.3
shows an example slide. Just connect the “Click to answer” button to the
Question3 (or whatever number you use) procedure, and when the user clicks
on the button, the InputBox will pop up asking for an answer. The figure shows
a button with the words “Click to answer,” but your button can contain the ques-
tion itself, the word “Question,” a question mark, or whatever else you like (as
long as the user knows to press the button to get and/or answer the question).
Note that this procedure was set up to work with the previous example in
which students can answer questions over and over again. To have it work with
any other examples, change the calls to RightAnswer3 and WrongAnswer3 to
RightAnswer and WrongAnswer.
This will take the answer that was typed, remove any spaces at the beginning or
end, and put the result (without the extra spaces) back into the answer variable.
Trim will turn “ Annapolis ” into “Annapolis.” This will not eliminate any
spaces in the middle, so “Ann apolis” will remain “Ann apolis.” If for some rea-
son you only want to remove the spaces before the answer or after the answer,
use LTrim or RTrim respectively.
If you are not concerned with how your students capitalize their answers,
LCase can set the answer to lowercase by adding:
answer = LCase(answer)
This takes the answer that the student typed, converts all capital letters to lower-
case letters, and puts the lowercase version back in the variable answer. This
will change “Annapolis,” “AnNaPolis,” and “AnnApolis” to “annapolis.” If you
are testing to make sure the student knows to capitalize the first letter of a city
name, don’t use LCase.
Include as many or as few different alternatives as you like. Just remember that if
you used LCase, all your alternatives must be lowercase.
If we use all our tricks (ignoring extra spaces, accepting any capitalization,
and allowing alternative answers), our procedure will look like this:
102 Quizzes and Tests
Sub Question3()
Dim answer
The exact same procedures can be used for any short-answer question. Sim-
ply change the InputBox statement to include your question and change the If
statement to include the correct answer(s) for your question.
The most significant changes to the code are related directly to our two ex-
tensions:
Here is the complete code (new lines and procedures are indicated by the
comment ‘ADDED):
Dim numCorrect As Integer
Dim numIncorrect As Integer
Dim userName As String
Dim q1Answered As Boolean
Dim q2Answered As Boolean
Dim q3Answered As Boolean
Dim answer1 As String 'ADDED
Dim answer2 As String 'ADDED
Dim answer3 As String 'ADDED
Dim printableSlideNum As Long 'ADDED
Sub GetStarted()
Initialize
YourName
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Initialize()
numCorrect = 0
numIncorrect = 0
q1Answered = False
q2Answered = False
q3Answered = False
printableSlideNum = ActivePresentation.Slides.Count + 1 'ADDED
End Sub
Sub YourName()
userName = InputBox(Prompt:="Type your name")
End Sub
Sub DoingWell()
MsgBox ("You are doing well, " & userName)
End Sub
Sub DoingPoorly()
MsgBox ("Try to do better next time, " & userName)
End Sub
Sub Answer1GeorgeWashington()
If q1Answered = False Then
numCorrect = numCorrect + 1
answer1 = "George Washington" 'ADDED
End If
q1Answered = True
DoingWell
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Answer1AbrahamLincoln()
If q1Answered = False Then
numIncorrect = numIncorrect + 1
answer1 = "Abraham Lincoln" 'ADDED
End If
q1Answered = True
DoingPoorly
End Sub
104 Quizzes and Tests
Sub Answer2Two()
If q2Answered = False Then
numCorrect = numCorrect + 1
answer2 = "2" 'ADDED
End If
q2Answered = True
DoingWell
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Answer2Four()
If q2Answered = False Then
numIncorrect = numIncorrect + 1
answer2 = "4"
End If
q2Answered = True
DoingPoorly
End Sub
Sub Question3()
Dim answer
Sub RightAnswer3()
If q3Answered = False Then
numCorrect = numCorrect + 1
End If
q3Answered = True
DoingWell
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub WrongAnswer3()
If q3Answered = False Then
numIncorrect = numIncorrect + 1
End If
q3Answered = True
DoingPoorly
End Sub
Set printableSlide = _
ActivePresentation.Slides.Add(Index:=printableSlideNum, _
Layout:=ppLayoutText)
printableSlide.Shapes(1).TextFrame.TextRange.Text = _
"Results for " & userName
printableSlide.Shapes(2).TextFrame.TextRange.Text = _
"Your Answers" & Chr$(13) & _
"Question 1: " & answer1 & Chr$(13) & _
"Question 2: " & answer2 & Chr$(13) & _
"Question 3: " & answer3 & Chr$(13) & _
"You got " & numCorrect & " out of " & _
numCorrect + numIncorrect & "." & Chr$(13) & _
"Press the Print Results button to print your answers."
Set homeButton = _
ActivePresentation.Slides(printableSlideNum).Shapes.AddShape _
(msoShapeActionButtonCustom, 0, 0, 150, 50)
homeButton.TextFrame.TextRange.Text = "Start Again"
homeButton.ActionSettings(ppMouseClick).Action = ppActionRunMacro
homeButton.ActionSettings(ppMouseClick).Run = "StartAgain"
Set printButton = _
ActivePresentation.Slides(printableSlideNum).Shapes.AddShape _
(msoShapeActionButtonCustom, 200, 0, 150, 50)
printButton.TextFrame.TextRange.Text = "Print Results"
printButton.ActionSettings(ppMouseClick).Action = ppActionRunMacro
printButton.ActionSettings(ppMouseClick).Run = "PrintResults"
ActivePresentation.SlideShowWindow.View.Next
ActivePresentation.Saved = True
End Sub
The most important thing you need to know about this script is how to add
more questions. If you understand the explanation of the script below, that is
great, and you will have a better ability to change aspects of the script. But if you
don’t understand the script, you can still add questions. Almost everything you
need to do to add questions is the same as in previous sections:
The PrintablePage procedure creates the page. Figure 7.4 shows an example
of this slide.
The following line creates a slide and stores it in the variable
printableSlide:
Set printableSlide = _
ActivePresentation.Slides.Add(Index:=printableSlideNum, _
Layout:=ppLayoutText)
How Did You Do: Reporting Results to the Teacher 107
9 is the size of the font, so you can choose a different number for a smaller or
larger font. Note that some versions of PowerPoint (2002 and above) automati-
cally change the font size for you so your text fits the text box. However, if you
use those versions, you might consider changing the font yourself in case your
presentation is used with an earlier version of PowerPoint.
Next we need to add buttons to our new slide. The following line adds a
custom button in the top left of the screen (coordinates 0,0) that is 150 pixels
wide and 50 pixels tall. A custom button has no icon in it.
108 Quizzes and Tests
Set homeButton = _
ActivePresentation.Slides(printableSlideNum).Shapes.AddShape _
(msoShapeActionButtonCustom, 0, 0, 150, 50)
Because we stored the button in the variable homeButton, we can use that
variable to change the attributes of the button. We need to put some text in the
button. The text “Start Again” will appear in the button:
homeButton.TextFrame.TextRange.Text = "Start Again"
Then we make the button clickable and assign a procedure (in this case, the
StartAgain procedure) to the button:
homeButton.ActionSettings(ppMouseClick).Action = ppActionRunMacro
homeButton.ActionSettings(ppMouseClick).Run = "StartAgain"
The code for the Print Results button is almost identical, so if you under-
stood the code above you don’t need any explanation for the Print Results button.
Finally, we want to go to the slide (ActivePresentation.SlideShowWindow.
View.Next) that we just created and fool PowerPoint into thinking that the
presentation does not need to be saved (ActivePresentation.Saved = True—
see “Saving and Quitting” in Chapter 8 for more information about this line).
The PrintResults procedure has two lines:
ActivePresentation.PrintOptions.OutputType = ppPrintOutputSlides
ActivePresentation.PrintOut From:=printableSlideNum, _
To:=printableSlideNum
The first line makes sure that PowerPoint knows it is going to print one slide per
page. The second line actually prints the single slide that we just created. If our
printable slide is slide number 6 (and thus printableSlideNum is 6), that line
says to print from slide 6 to 6.
The last procedure is StartAgain. This simply goes to the first slide, de-
letes the slide that was just printed (ActivePresentation.Slides
(printableSlideNum).Delete), and makes sure that PowerPoint doesn’t
ask you to save.
You might want to know what buttons will be tied to the last three proce-
dures. PrintablePage, instead of the Feedback procedure from earlier exam-
ples, will be tied to the “How Did I Do” button. But what about the last two
procedures? That is a trick question. You don’t tie them to any buttons. We have
used VBA to create the buttons and tie them to procedures as part of the
PrintablePage procedure. Creation of the buttons and tying them to proce-
dures is taken care of automatically with our VBA.
Learn First, Ask Questions Later: The Tutorial and Quiz 109
Another possibility is to indicate that a menu item has been visited by putting
a symbol next to it, such as a check mark or a smiley face. You might create a tuto-
rial and quiz like the one shown in Figure 7.5 (page 110). This simple tutorial has
three parts: The Executive Branch, The Legislative Branch, and The Judicial
Branch. Students may choose these parts of the tutorial in any order. Smiling
sunshines next to the buttons indicate those sections of the tutorial that have already
110 Quizzes and Tests
been completed. The smiling sunshines (or whatever symbols or pictures you like)
can be created with any traditional PowerPoint tools (drawing, clip art, inserting a
picture, etc.).
In the figure, slide numbers are shown in the upper left corner of the slide,
and the boxes indicate which procedures are tied to which buttons. Notice in the
figure that some of the buttons do not use VBA; they use traditional PowerPoint
hyperlinks. Figure 7.6 shows the VBA code. Note that the quiz portion of this
example is fairly simple (it doesn’t keep score), but you can use any of the
Learn First, Ask Questions Later: The Tutorial and Quiz 111
examples from this chapter and plug the code into the Initialize procedure
(add that code to earlier Initialize procedures; never create two separate
Initialize procedures) and add the ReturnToMenuFromPart1,
ReturnToMenuFromPart2, ReturnToMenuFromPart3, and JumpToMenu
procedures from Figure 7.6.
Figure 7.6. VBA Code for Menus with Feedback in Tutorial and Quiz
112 Quizzes and Tests
The important parts of this example are shapes 6, 7, and 8 on slide 2 (the
menu slide). These are the smiling sunshine pictures that indicate that a section
of the tutorial has been completed. Of course, the numbers might change de-
pending on how you create the menu slide, and you might have more menu items
and thus more smiling sunshines (or whatever picture you choose).
As the shapes are the important parts, all but one of the new procedures deal
with the shapes. The three lines in the Initialize procedure, like
ActivePresentation.Slides(2).Shapes(6).Visible = False
hide the shapes so that when the student reaches the menu for the first time, the
shapes are hidden. If your menu is not on slide 2, change the 2 to something else.
In addition, this hides shape 6, so there is one line for each smiling sunshine,
each with a different number.
Next we need to show the shapes at the appropriate time. They will be
shown when clicking on the button that returns from each part of the tutorial.
The three ReturnFromMenuFromPart procedures show the appropriate shape
with
ActivePresentation.Slides(2).Shapes(6).Visible = True
Note that the shape numbers are 2, 3, and 4 because we are referring to the num-
bers of the buttons, not the numbers of the smiling sunshines. In our
ReturnFromMenuFromPart procedures, we need to change the color of the
buttons to a different color, using lines like the following:
ActivePresentation.Slides(2).Shapes(2).Fill.ForeColor.RGB = vbMagenta
Now that your students know where they have been, in the next section, we
will add a few lines so they have to complete the tutorial before taking the quiz.
Learn First, Ask Questions Later: The Tutorial and Quiz 113
Change False to True to show it, and change 5 to some other number if your
Quiz button is not shape 5. Also note that the Quiz button should be hidden at the
beginning so HideQuizButton is added to Initialize.
DoWeShowQuizButton asks a three-part question: Is part 1 of the tutorial
completed, is part 2 of the tutorial completed, and is part 3 of the tutorial completed?
If all three parts have been completed—(visitedPart1, visitedPart2, and
visitedPart3 have each been set to True)—then we show the Quiz button. If
any part has not been completed (any visitedPart is not True), then we hide
the Quiz button.
Figure 7.7. VBA Code to Hide and Show the Quiz Button
Conclusion 115
If your tutorial has more parts, you will need to do the following:
• Add more variables, such as visitedPart4 and visitdPart5,
and declare them with Dim statements.
• Initialize the added variables in the Initialize procedure, with
lines like visitedPart4 = False.
• Add more procedures (such as ReturnToMenuFromPart4 and
ReturnToMenuFromPart5) to return to the menu from the added parts
of the tutorial. Be sure to tie the menu buttons to those parts of the tutorial.
• Add more parts to the If question in DoWeShowQuizButton. For
example:
• Add more smiling sunshine pictures next to the additional menu but-
tons. Hide them in the Initialize procedure and show them in the
additional ReturnToMenuFromPart procedures.
Of course, this same structure does not need to be used for a tutorial and
quiz; it could be used for anything with several parts. If you want your students
to complete certain parts before completing some other parts, you can use ex-
actly the same code.
Conclusion
You now have seen several examples of ways to create tutorials and quiz-
zes. You can create different kinds of questions and keep and report scores in
different ways. In the next chapter, you learn a few more scripting tricks and get
some more explanation about some programming structures.
116 Quizzes and Tests
Exercises to Try
Ä In the section “Try Again and Again: Answer Again After It’s
Right,” we created a simple multiple-choice quiz that only
counts the student’s first try on each question. Try to add two
more multiple-choice questions to the quiz. Remember that you
will need additional variables q3answered and q4answered as
well as RightAnswer3, WrongAnswer3, RightAnswer4, and
WrongAnswer4 procedures.
Introduction
In Chapter 7 you used all the tricks you had learned in previous chapters to
create quizzes and tests. This chapter will add to your scripting bag of tricks to
help you do more with the examples from previous chapters, create some of your
own examples, and understand some of the things you have already used. You
will learn more about If statements and loops (like the While loops you have
already seen) and about timed functions, automatically saving or not saving your
presentation, naming objects and slides, and random numbers. The chapter con-
cludes with a complete example that uses random numbers to randomly show
different questions from a large pool.
Vocabulary
• Array • Loop
• Conditional • Nested If
• Dirty • Parameter
• Infinite loop • Stopping condition
118 More Tricks for Your Scripting Bag
The If statement asks a question. If the answer is yes, we do the first thing. If the
answer is no, we do what comes after the Else. The above code is exactly the
same as the English sentences:
If it is raining Then
We will play inside
Otherwise
We will play outside
The question can be anything that returns a True or False answer. We might
compare the value of a variable to something. For example:
If numCorrect > 6 Then
MsgBox("You got a lot of questions right.")
Else
MsgBox("You can do better than that.")
End If
In this case, if the variable numCorrect (presumably that was used by some
other procedures to count the number of questions that were answered correctly)
is greater than 6, a MsgBox will pop up saying “You got a lot of questions right.”
If the variable numCorrect is not greater than 6 (it is 6 or less), then the MsgBox
will say “You can do better than that.”
This can be extended to check more than one thing using ElseIf. You
might say: if it is raining, we will play inside; if it is snowing, we will build
snowmen; otherwise, we will play baseball.
If raining = True Then
PlayInside
ElseIf snowing = True Then
BuildSnowmen
Else
PlayBaseball
End If
Conditionals: The If Statement 119
In this case, we ask one question. If the answer is yes, we do the first thing. If the
answer is no, we ask a second question. If the answer to the second question is
yes, we do the second thing. If the answer to the first question is no, and the an-
swer to the second question is no, we do the third thing. Note, we can ask as
many questions as we want by putting more and more ElseIf statements. Imag-
ine a grading program that converts numbers to letter grades:
Sub WhatsMyGrade()
If gradeNum >= 90 Then
MsgBox("You got an A")
ElseIf gradeNum >= 80 Then
MsgBox("You got a B")
ElseIf gradeNum >= 70 Then
MsgBox("You got a C")
ElseIf gradeNum >= 60 Then
MsgBox("You got a D")
Else
MsgBox("You got an F")
End If
End Sub
This assumes that a variable named gradeNum has been given a value some-
where else. It then asks the question, is this grade greater than or equal to 90? If
the answer is yes, it pops up a box with the message “You got an A,” and it stops.
However, if the answer is no, it asks the next question: is this grade greater than
or equal to 80? If the answer to this question is yes, it pops up a box with the mes-
sage “You got a B,” and it stops. It keeps asking questions as long as the answers
are no. If all the answers are no, it reaches the Else statement and pops up a box
with the message, “You got an F.”
Note that you can do more than one thing in response to a yes answer. You
might, for example, pop up a MsgBox and then move to the next slide under one
condition, but pop up a different MsgBox and then move to the previous slide un-
der a different condition:
If gradeNum >= 90 Then
MsgBox ("You got an A.")
ActivePresentation.SlideShowWindow.View.Next
Else
MsgBox ("You need to work harder.")
ActivePresentation.SlideShowWindow.View.Previous
End If
Because you can do several things in response to a yes answer, you can do sev-
eral complicated things. The above example uses two simple statements, but you
can have as many statements as you want. Some of these statements might be
complicated structures like loops (see the next section) and other If statements.
When you put an If block inside an If block, it is called a nested If. If the an-
swer to your question is yes, you might want to ask other questions:
120 More Tricks for Your Scripting Bag
Pay careful attention to the way this example is indented. Although you don’t
have to type it indented in this way, it is much easier to understand with the indent-
ing. You can see that the question is asked: Is gradeNum greater than 90? Every-
thing between the first If and the Else is indented to show that it is what to do if
the answer is yes. Part of what to do is to ask another question. That question asks
if previousGradeNum also is greater than 90. This question will only get asked
if gradeNum is greater than 90. The indenting helps to see the nesting. It is partic-
ularly helpful if the nested If block is more complicated, with its own Else, for
example. The Else should always be lined up with the If with which it goes.
The If statement is very powerful. It is one of the things that allows for in-
teraction. Without conditional statements, every user would do exactly the same
thing as the previous user.
Looping
If statements allow you to make choices based on whether or not a condi-
tion is true. Looping allows you to do something over and over again. How many
times is based on a condition, that is, a question like what you ask in an If state-
ment. This is known as the stopping condition. In some types of loops (such as a
While loop), this question is phrased as a keep going question, and in other
types of loops (such as a For Next loop), the condition is based on how many
times you say you want to loop. However the question is phrased, the loop needs
to know when to stop.
While Loops
There are several types of loops, and you might want to explore different
ones, but once you know one, you can do just about anything you might want to
do. Let’s look at the While loop. The While loop asks a question and keeps loop-
ing while the answer to the question is yes. My four-year-old daughter might ask
“Is it still raining?” She might ask this over and over again until it has stopped rain-
ing. As long as it is raining, she will add another block to her tower and ask again:
While StillRaining
AddBlockToTower
Wend
PlayOutside()
Looping 121
In this case, the question is: Is it still raining? If the answer is yes, add another
block to the tower. The Wend statement stands for While END and simply limits
the loop. Whatever is between the While and Wend statements will happen over
and over again until the answer to the question is no. Many things can happen
between a While and Wend; it is not limited to one statement. This loop will
keep executing as long as it is still raining. Once it stops, the answer to the ques-
tion will be no, and whatever is after the Wend will be executed. In this case, my
daughter will finally go play outside.
We could use this to ask a question until the right answer is entered. For
example:
Sub HowManyPlanets()
Dim answer As String
answer = ""
While answer <> "nine" And answer <> "9" And answer <> "Nine"
answer = InputBox _
("How many planets are there in our solar system?")
Wend
End Sub
answer = ""
count = 0
While answer <> "nine" And answer <> "9" And answer <> "Nine" _
And count < 3
answer = InputBox _
("How many planets are there in our solar system?")
count = count + 1
Wend
End Sub
count is still less than 3, we ask for the answer again and add 1 to count (count
= count + 1). Once we have asked three times, count will be 3. Then, the
question in our While statement will be no because count < 3 will be False.
In that case, we will stop looping.
When the conditions are complicated, we might want to do what we have
done with the YourName procedure (see Chapter 5):
Sub YourName()
Dim done As Boolean
done = False
While Not done
userName = InputBox(prompt:="Type your name", _
Title:="Input Name")
If userName = "" Then
done = False
Else
done = True
End If
Wend
End Sub
In this procedure, we use the variable done to determine whether we are finished
looping. The If block could have all been included in the While statement, elimi-
nating the need for done. This would have made for short VBA code, but it would
have been very difficult to understand, particularly if the stopping condition was
more and more complicated. Setting up an If block allows you to check as many
conditions as you like and set done based on those conditions. Then, the only
question for While is: Are we done or not? If we are not done, keep looping.
Do Loops
Do loops are similar to While loops. They allow you to specify either a
While condition (keep going while something is True) or an Until condition
(keep going until something is True). They also let you specify the condition
(ask the stopping question) at the beginning or the end. If the condition is at the
beginning, the loop might never run (not even once). If the condition is at the
end, the loop will always run at least once. Here are some simple examples:
Do
answer = InputBox("How many planets are in the solar system?")
Loop Until answer = "9"
Do
answer = InputBox("How many planets are in the solar system?")
Loop While answer <> "9"
In the first example, the loop will run at least once and ask the question: How
many planets are in the solar system? After running the loop once, it will check to
see if answer is 9. If it is, it will stop. If it isn’t, it will loop until the answer is 9.
In the second example, the loop will run at least once and ask the question:
How many planets are in the solar system? After running the loop once, it will
check to see whether answer is not 9. It will keep looping while the answer is
not 9. Note, this works exactly the same as the first example, but sometimes it is
easier to ask a positive question than a negative question, particularly if the ques-
tion has many parts with And and Or.
In the third and fourth examples the condition will be checked before the
loop runs. In the third example, the loop will only run if count is less than 3, and
it will keep looping while count is less than 3. In the fourth example, the loop
will stop running if count is greater than or equal to 3, and it will keep looping
until count is greater than or equal to 3. Like the first two examples, these ex-
amples have exactly the same results, but sometimes it is easier to ask a positive
question, and sometimes it is easier to ask a negative question.
This uses the variable i and counts from 1 to 10. That is, i starts out at 1, and the
loop keeps looping (everything between the For line and the Next line is run)
over and over again, adding 1 to i, up to and including the time that i becomes
10. Next i says to go back to the beginning of the loop and increase i. As with
all the other loops, you can put as many lines as you like between the For line
and the Next line, and all those lines will be executed over and over again.
For Next, Do, and While loops can get more complicated, but these basic
loops should suit most of your purposes.
124 More Tricks for Your Scripting Bag
Infinite Loops
Before we leave looping, a word of warning about infinite loops: In all of
our loops, we have set stopping conditions; that is, we have told the loop when to
stop looping. What if the stopping condition is never met? Then you have an in-
finite loop, a loop that never stops. Here is a simple example (don’t type this):
While 8 > 7
MsgBox ("Eight is still greater than seven.")
Wend
Because 8 > 7 is always True (i.e., 8 is always greater than 7), this loop will
never stop. Usually, you won’t have something so obvious. You will either type
something wrong (perhaps > when you meant <), or you will have a complicated
expression with variables, and you won’t realize that the condition for stopping
never can be met.
If you get stuck in an infinite loop, it will appear that PowerPoint has
frozen. In all likelihood, you will have to force PowerPoint to quit. On a Win-
dows computer, you can use Ctrl-Alt-Delete (i.e., hold down the Ctrl and Alt
keys while hitting the Delete key). Depending on the version of Windows you
are running, you will either restart your computer or be given the option to stop
an unresponsive application (PowerPoint, in this case). If you are on a
Macintosh, you will have to hit Command-Option-Esc (i.e., hold down the Com-
mand and Option keys while hitting the Esc key; note that the Command key is
the one with the picture of the apple on it). If you do this, you will lose any
changes you made to your presentation since you saved it last. That is why it is
very important to save changes often, particularly when you are working with
loops. In fact, when testing out a loop, you should probably save your changes
before you put PowerPoint in Slide Show View.
Parameters
Sometimes a procedure has all the information it needs when you write it.
Sometimes it gets information from variables where we have stored information
(as long as the variables are declared at the beginning of the module). At other
times we want to give a procedure extra information as we go. We can do this
with something called a parameter. A parameter is extra information sent to a
procedure when it is called. We have used parameters when calling procedures
(something as simple as a MsgBox takes a parameter: the text to display), but we
have not used parameters in procedures we have written. Parameters are a very
useful tool for programmers, but they can be a bit tricky. Following is a brief ex-
planation of parameters, so when you see them in examples (such as the timed
functions in the next section), you’ll understand them.
Imagine that you wanted to put up a MsgBox with different messages for
different occasions. Perhaps the message is the same except for one thing. For
Timed Functions 125
example, you might want to say, “You are doing well, Ella” at some point and
“You are doing poorly, Ella” at another time. We have done this with two sepa-
rate procedures in the past, but we could write one procedure with a parameter:
Sub Doing(doingHow As String)
MsgBox ("You are doing " & doingHow & ", " & username)
End Sub
For something this simple, the parameter may not be worth the effort, but it can
be very useful if the procedure that takes the parameter is more complicated. In
this case doingHow is the parameter. It is a String because it is declared in the
Sub statement to be a String, so another procedure would call doingHow with
a String in parentheses. For example Doing("well") would pop up a
MsgBox that says, “You are doing well, Ella” (assuming the userName was
“Ella”) . This might be called from a procedure that included the following If
block:
If numCorrect > 10 Then
Doing ("superbly")
ElseIf numCorrect > 8 Then
Doing ("well")
ElseIf numCorrect > 5 Then
Doing ("OK")
ElseIf numCorrect > 3 Then
Doing ("Poorly")
Else
Doing ("Very Poorly")
End If
Parameters can be of any type. We used a String in this example, but you can
pass various kinds of numbers or Booleans or even objects such as shapes. You
can pass more than one parameter as well if you need different kinds of informa-
tion passed to a procedure, but for most of your purposes, if you need a parame-
ter at all, one will suffice. Parameters can be tricky and complicated, so we will
not use them a lot, but now you have a basic understanding of how they work in
case you see them in some examples.
Timed Functions
Most actions in PowerPoint happen because the user did something, such
as pressing a button to go to another slide. Sometimes, however, you want things
to happen whether or not the user has done anything. For example, you might
want a sound to start playing a few seconds after the slide is shown. You might
want the presentation to go from slide to slide on its own. You might want infor-
mation to pop up on the screen, then go away, and then have other information
pop up on the screen.
As soon as the user clicks on a button tied to a script with timing features
(such as the button to go to another slide), you can start anything happening after
126 More Tricks for Your Scripting Bag
any length of time. Of course, the standard “Custom Animation” choice from the
Slide Show menu can allow objects to appear with timing, but you might want to
do more. If you want something to happen after a short delay, you can use the
following procedure:
Sub Wait()
waitTime = 5
start = Timer
While Timer < start + waitTime
DoEvents
Wend
End Sub
This procedure waits five seconds. Timer is a function that returns the number
of seconds since midnight (e.g., at 12:01 A.M., Timer will return 60). waitTime
is a variable used to tell how many seconds to wait (change the number 5 to any
number to have this procedure wait that number of seconds). At the beginning of
the procedure, the variable start is set to the current time in seconds (as re-
turned by Timer). Next, we loop until the current time is less than the time we
started plus the waitTime (which is five seconds in our example). Inside the
loop (between the While statement and the Wend statement), we run DoEvents.
This lets VBA check to see if anything else is happening, particularly things that
the user might do, such as hit the Escape key or click on another button. If you
don’t want the user to do anything while you are waiting, leave out DoEvents.
Be careful! If you make a mistake (perhaps you set the waitTime to five mil-
lion seconds instead of five seconds or you mistyped Timer in the Do While state-
ment), you could end up in an infinite loop, essentially freezing PowerPoint. If you
feel you must stop the user from doing anything while VBA waits, leave DoEvents
in your procedure until you are sure everything works. Once you are certain every-
thing works, delete the DoEvents line. This will allow you to stop your presenta-
tion by hitting the Escape key while you are still testing your procedure.
Before we continue, get a new PowerPoint presentation and type the Wait
procedure. Then add the following procedure:
Sub HelloWaitGoodbye()
MsgBox ("Hello")
Wait
MsgBox ("Goodbye")
End Sub
When you run HelloWaitGoodbye, you should see a MsgBox that says
“Hello.” After you click OK to dismiss the MsgBox, you should see a MsgBox
that says “Goodbye,” but only after a delay of five seconds.
Now suppose that you want to wait, but not always for five seconds. You
could write several different procedures (Wait5, Wait10, Wait60, etc.) to wait
different amounts of time, but we can use a simple parameter to write one proce-
dure that can wait different amounts of time.
Saving and Quitting 127
In this procedure, instead of setting the waitTime to five, we call Wait with
however long we want to wait (e.g., Wait (60) would wait sixty seconds).
Timed functions are useful if you want to give your users a chance to do
something before moving on. For example, you might display a text box, wait a
short time, then display a second text box. This allows the user to focus on the
first text box before getting too much information. Be careful with timed func-
tions, because different people read at different speeds. If you set your wait times
too long, some people will get restless waiting for the next thing to happen. If
you set them too short, some people will not have time to finish the first thing.
Some timing can be done automatically without VBA. You can use Custom
Animation to have things appear and disappear as much as you like. However, as
with many things that you can do without VBA, you might find that you can do
more with VBA. For example, you might ask the user how fast to go:
speed = InputBox ("How fast do you read [fast, medium, slow]?")
Now when it is time to wait, you might do something like the following:
If speed = "fast" Then
Wait (5)
ElseIf speed = "medium" Then
Wait (10)
Else
Wait (15)
End If
You should note that wait times are approximate. This does not work well if you
need precise timing, but it should do roughly what you want.
we didn’t want to save the slide. In this case, PowerPoint knows that the presen-
tation has been changed, so we needed to make it think that it was not changed.
Of course, changes that PowerPoint thinks need to be saved do not have to be as
large as adding a slide. Changes as small as hiding or showing an object, such as
a shape that indicates the student has visited part of the tutorial in “Learn First,
Ask Questions Later” in Chapter 7, will make PowerPoint think your presenta-
tion needs to be saved.
In other cases, we might want the changes to be saved. In Chapter 10 is an
example in which important slides are being added to the presentation. As users
go through the project, they might be asked for information, which is stored on a
newly created slide. Later, the designer will go through the presentation and look
at those slides . . . only if they were saved.
Fortunately, it is very easy to control whether or not your presentation is
saved. Four simple procedures will help you:
Sub MakeNotDirty()
ActivePresentation = True
End Sub
Sub Save()
ActivePresentation.Save
End Sub
Sub Quit()
Application.Quit
End Sub
Sub QuitAndSave()
Save
Quit
End Sub
In computer terms, a presentation that is changed but not saved is called dirty.
The status of the current presentation (whether it is dirty or not, i.e., whether it
has been changed or not since the last time it was saved) is stored in the variable
ActivePresentation.Saved. Even if the presentation has been changed, we
can fool PowerPoint into thinking that it hasn’t been changed by setting the
ActivePresentation.Saved to True as in the MakeNotDirty procedure
above. If you call this procedure (or simply put the line ActivePresentation.
Saved = True into some other procedure), PowerPoint will not ask you if you
want to save the presentation when you quit. Be sure you do this every time you
make a change because the next change you make will make the presentation
dirty again, setting ActivePresentation.Saved back to False.
You probably want to do this right away when you make a change. In fact,
you should do it in the procedure that makes the change. For example:
Saving and Quitting 129
Sub StartAgain()
ActivePresentation.SlideShowWindow.View.GotoSlide (1)
ActivePresentation.Slides(printableSlideNum).Delete
ActivePresentation.Saved = True
End Sub
This procedure is from the example in “How Did You Do: Reporting Results to
the Teacher” in Chapter 7. This procedure jumps to the first slide and deletes the
last slide (which had been created temporarily in an earlier procedure). Once it
deletes the last slide, the presentation is dirty, but we don’t want anyone to be
asked to save it. By setting ActivePresentation.Saved to True, the stu-
dents won’t be asked.
For the cases where you want to save a presentation, you can use the Save
procedure above. As long as the place where the presentation is running is a lo-
cation that can be saved (unlocked disk, network folder where the user has write
privileges, etc.), Save will save the presentation without the user even knowing
(unless it is saving something to a slow device like a floppy disk, in which case it
might take a few seconds to save). You would use this (or simply the line
ActivePresentation.Save) immediately after doing something that you
want saved. An example of this can be found in Chapter 10:
Sub WorkTogether()
GetNameEmailIdea
GoToWorkTogether
AddWorkTogetherSlide
Save
End Sub
is dirty; it saves regardless. Thus, you don’t want to save if you have made
changes that you don’t want saved (even if you have called MakeNotDirty).
Being sure that changes are saved or not saved as you, the designer, know
they should be is very important. Your students won’t know whether they should
save or not, and they shouldn’t be bothered by being asked. The procedures in
this section will help you manage the saving or not saving of your presentation.
Object Names
In Chapter 6 we discussed how to reference objects by their names, and we
noted how difficult it is to remember the name of an object. The following
scripts can be used to find the name of an object and set the name of an object.
Note that all other scripts in this book are designed to be run in Slide Show View.
These scripts are designed to be run in Edit View.
The two procedures that we need are GetObjectName and
SetObjectName. GetObjectName finds out what the name of an object is.
SetObjectName asks you to type a new name for an object.
If you run the GetObjectName script while an object is selected, a
MsgBox will pop up with the object’s name. If you run SetObjectName, an
InputBox will allow you to enter a name for an object. These scripts check to
make sure that one and only one object is selected, because you can’t get or
change the name of more than one object at a time.
Sub GetObjectName()
If ActiveWindow.Selection.Type = ppSelectionShapes _
Or ActiveWindow.Selection.Type = ppSelectionText Then
If ActiveWindow.Selection.ShapeRange.count = 1 Then
MsgBox (ActiveWindow.Selection.ShapeRange.Name)
Else
MsgBox ("You have selected more than one shape.")
End If
Else
MsgBox ("No shapes are selected.")
End If
End Sub
Sub SetObjectName()
Dim objectName As String
If ActiveWindow.Selection.Type = ppSelectionShapes _
Or ActiveWindow.Selection.Type = ppSelectionText Then
If ActiveWindow.Selection.ShapeRange.count = 1 Then
objectName = InputBox(prompt:="Type a name for the object")
objectName = Trim(objectName)
What’s in a Name? Finding and Changing Object and Slide Names 131
If you are trying to understand these procedures, pay careful attention to the
nested If statements and how they are indented in the example.
The heart of these procedures is ActiveWindow.Selection.
ShapeRange.Name. This looks at the Name property of the currently selected
shape. In GetObjectName, we simply return this name in a MsgBox. In
SetObjectName, we set this with whatever is typed in an InputBox. The rest
of each of the procedures is to make sure an object is selected and to clean up
what you typed for the object’s name.
If you run the GetObjectName script while an object is selected, a
MsgBox will pop up with the object’s name. You can then use this name in
quotes instead of an object’s number. For example, if you wanted to hide an ob-
ject named “Picture 6,” you can use:
ActivePresentation.SlideShowWindow.View.Slide. _
Shapes("Picture 6").Visible = False
As you recall from Chapter 6, once you add an object to your slide, its name, un-
like its number, will not change unless you change it, so this line of code will al-
ways work even if you change the animation order or delete other objects on the
slide. Even if you don’t name your own objects, each new object that is added to
a slide is given a name that is different from all other objects that have ever been
added to that slide.
When you run SetObjectName, an InputBox will allow you to enter a
name for an object. Trim is used to delete any extra spaces before and after the
name you type. The procedure also checks to make sure you typed something,
because you don’t want to give an object a blank name.
GetObjectName and SetObjectName check to make sure that one and
only one object is selected, because you can’t get or set the name of more than
one object at a time. If you are looking for a simpler way to do the same things,
you can try the following scripts, but you are responsible for making sure that
you have selected one and only one object.
132 More Tricks for Your Scripting Bag
Sub GetObjectName()
MsgBox (ActiveWindow.Selection.ShapeRange.Name)
End Sub
Sub SetObjectName()
Dim objectName As String
If you try to run either of these procedures without having one object selected,
you will get an error message. If you try to give an object the same name as an-
other object on that slide, you will also get an error message, so be sure to give
each object on a slide a different name.
Because these procedures run in Edit View in PowerPoint (not from Slide
Show View or from the VBA Editor), we cannot create a button on a slide to run
them. The easiest way to run a script in Edit View is to select “Macro” from the
Tools menu and choose “Macros” from the flyout menu (or hit Alt-F8 on a Win-
dows computer or Option-F8 on a Macintosh). Select the procedure name that
you want to run, and click on the Run button (see Figure 8.1).
Slide Names
Just as object numbers can change, slide numbers can change as well. If you
are trying to go to a particular slide and you use a slide number, you might have a
problem if you delete or insert slides before that slide. Slide names never change
unless you change them. When a slide is created, it is assigned a name (Slide1,
Slide2, Slide3, etc.). These names are assigned in the order the slide is inserted,
not the order in which the slide is within the presentation. For example, if you
create a slide, it will be named “Slide1.” If you create another slide, it will be
named “Slide2.” If you create a third slide between “Slide1” and “Slide2,” it will
be the second slide in the presentation, but it will be named “Slide3.”
If you move slides around a lot, you will have a hard time remembering
their names. Use GetSlideName and SetSlideName to find out the name of a
slide and change the name of a slide:
Sub GetSlideName()
MsgBox ActiveWindow.View.Slide.Name
End Sub
Sub SetSlideName()
Dim slideName As String
This hides shape 6 on slide 2. If we were to name our menu slide “Menu” and the
object to be hidden “MenuMark1,” we could use the following line instead:
ActivePresentation.Slides("Menu").Shapes("MenuMark1").Visible = False
134 More Tricks for Your Scripting Bag
Although this is a little more complicated than simply using a number, it is a lot
safer because slide names never change unless you change them.
You never have to use object names or slide names. You can do everything
you want with numbers. However, as you make more complicated presentations
with more slides and more objects, and you begin to change slides and objects
around, using names will save you a lot of grief. When you move objects, delete
slides, reorder slides, insert slides, change the animation order of objects, etc.,
your slide names will remain the same, and your VBA code will continue to
work.
Arrays
Computer programs can use many different kinds of data structures. Under-
standing data structures is an important part of computer programming. How-
ever, throughout this book I have avoided turning you into a programmer and
only shown you what you need to know to be a scripter. The topic of data struc-
tures is something you can avoid, but if you understand some basic data struc-
tures, they can make your life easier. In fact, some of the examples that you have
seen could have been simpler with some more advanced data structures. I have
made some earlier examples longer so that they would be easier to understand.
Data structures are a way to store information. In Chapter 5 we used the box
analogy to show how variables can be used to store information, but sometimes
information can be stored more easily in something other than a single box. A
collection of numbered boxes might be more suitable. This collection of num-
bered boxes is an array. You might think of an array as an egg carton, with sec-
tions for each of several eggs.
In several earlier examples, such as the example in “Try Again and Again:
Answer Again After It’s Right” from Chapter 7, we created our own numbered
variables. In that example, we used q1Answered and q2Answered to store the
information about whether question 1 was answered and whether question 2 was
answered. If we had more questions, we would add more variables. This is easy
to understand but difficult to type, particularly if we have a lot of questions. This
could be simplified with an array.
Arrays 135
The first step is to declare the array. Suppose we have five questions. With-
out an array we would do the following to declare our five variables:
Dim q1Answered As Boolean
Dim q2Answered As Boolean
Dim q3Answered As Boolean
Dim q4Answered As Boolean
Dim q5Answered As Boolean
This will give us an array that contains six boxes, numbered 0 through 5:
qAnswered(0), qAnswered(1), qAnswered(2), qAnswered(3),
qAnswered(4), and qAnswered(5). Note that we really only need five
boxes in our example, and we got six. There are many ways to avoid getting the
extra box, but unless you are an aspiring programmer, the easiest thing to do is
simply ignore box number 0.
Now, we can shorten our Initialize procedure. It won’t be shorter with
two questions (or significantly shorter with five), but when you create some-
thing with ten or twenty questions it will be much shorter:
Sub Initialize()
Dim i As Long
numCorrect = 0
numIncorrect = 0
For i = 1 to 5
qAnswered(i) = False
Next i
End Sub
This procedure uses a For loop, just like what we saw above in “Looping.” It
loops through each of the members of the qAnswered array and sets each to
False. In the original version, every time you added a new question, you would
need to add a new Dim statement and a new line in Initialize. Now, the only
thing you have to change is the number “5” in your Dim statement and in the For
line of your Initialize procedure.
Having a separate variable for each question was only a little inconvenient.
The biggest inconvenience was having a separate RightAnswer and
WrongAnswer procedure for each question. We needed this
1. to assign True or False to the correct qAnswered variable;
2. to know which question was being answered so we could know which
was the appropriate qAnswered variable for number 1; and
3. in later examples, to assign the actual answer to the correct answer
variable.
136 More Tricks for Your Scripting Bag
Our array takes care of number 1. Number 2 can be handled easily if our
questions are all in order. In our examples with the questions beginning on slide
2, each question is one less than the slide number (i.e., question 1 is on slide 2,
question 2 is on slide 3, etc.), so to get the question number, we simply subtract
one from the slide number (ActivePresentation.SlideShowWindow.
View.Slide.SlideIndex - 1). We’ll take care of number 3 in the next section.
Using the Dim statements and Initialize procedure from above and the
GetStarted, YourName, DoingWell, and DoingPoorly procedures from
any of the earlier examples, we can use the following RightAnswer procedure
and WrongAnswer procedure to replace all the specialized RightAnswer and
WrongAnswer procedures. The only thing you ever have to change is the num-
ber 5 in the Dim statement and the Initialize procedure. Just make this num-
ber equal to the number of questions you have.
Sub RightAnswer()
Dim thisQuestionNum As Long
thisQuestionNum = _
ActivePresentation.SlideShowWindow.View.Slide.SlideIndex - 1
If qAnswered(thisQuestionNum) = False Then
numCorrect = numCorrect + 1
End If
qAnswered(thisQuestionNum) = True
DoingWell
End Sub
Sub WrongAnswer()
Dim thisQuestionNum As Long
thisQuestionNum = _
ActivePresentation.SlideShowWindow.View.Slide.SlideIndex - 1
If qAnswered(thisQuestionNum) = False Then
numIncorrect = numIncorrect + 1
End If
qAnswered(thisQuestionNum) = True
DoingPoorly
End Sub
This says that we need an array qAnswered to hold Boolean values, but we
don’t know how many values we’ll need to hold. When we do know how many
values, we can use the ReDim statement to tell VBA.
The question is, how and when do we know how many values we need?
The answer is that we know right away, and we can tell by how many slides we
have. In our example, we have five question slides, one title slide, and one re-
sults slide, for a total of seven slides. That is, all but two of our slides (the title
slide and the results slide) are question slides. Thus our total number of ques-
tions is the total number of slides minus two:
ActivePresentation.Slides.Count - 2
We can use this in our Initialize procedure by assigning this value to a vari-
able (we’ll use numQuestions), using ReDim to tell VBA how many items we
need in qAnswered, and using this value in our For loop to initialize each item.
Sub Initialize()
Dim i As Long
Dim numQuestions As Long
numCorrect = 0
numIncorrect = 0
numQuestions = ActivePresentation.Slides.Count - 2
ReDim qAnswered(numQuestions)
For i = 1 To numQuestions
qAnswered(i) = False
Next i
End Sub
Using the new Dim statement and the new Initialize procedure, you
never have to change the VBA. This makes it easier for you because you can add
and change questions with no VBA changes, and it turns this into a powerful tool
for your students; they can make their own quizzes that use your VBA (see
Chapter 10 for more about templates). Some of you will want to teach your stu-
dents VBA, but most of you will not. If you can write the code, all they have to
do is create the questions and tie the buttons to the RightAnswer and
WrongAnswer procedures.
138 More Tricks for Your Scripting Bag
Short-answer questions will still need VBA to check the answer. You can
either:
• stick to multiple-choice questions and never touch the above code, or
• use short-answer questions by writing Question1, Question2,
Question3, etc., procedures for each short-answer question but
hav ing each Ques tion pro ce dure call RightAnswer and
WrongAnswer , not spe cialized RightAnswer1 and
WrongAnswer1 , RightAnswer2 and WrongAnswer2 ,
RightAnswer3 and WrongAnswer3 , etc., procedures.
With either choice, your VBA is greatly simplified. You could probably even
teach your students to copy and paste new question procedures, simply changing
the number of the question in the Sub line and the text for the question and right
answer.
This uses a special trick with parameters (see “Parameters”) . When a button is
pressed, it can pass the button itself as a parameter to the procedure that called it.
Normally, we use VBA to pass parameters (by putting them in parentheses when
we call a procedure), but in this case, clicking the button passes the parameter.
We just have to set up our procedure to store the parameter. In this example, we
used the variable answerButton. Once we have a pointer to the button itself
(i.e., answerButton), we can get the text that is in the button with
answerButton.TextFrame.TextRange.Text. If you have put the answer
in the text of the button, you can use that to get the answer that was chosen.
Which Button Did I Press? 139
Now we can store the answers for a printable slide without adding any extra
code for each multiple-choice question and without adding very much extra
code for each short-answer question. Our code for the simple three-question ex-
ample is a bit longer, but as you add more questions, the overall code will be
much shorter. In fact, just like the previous example, if you only use multiple-
choice questions, you do not have to change the code at all when you add
questions.
The new code follows. The GetStarted, YourName, DoingWell, and
DoingPoorly procedures are the same ones we have used many times before.
We can also use the new RightAnswer and WrongAnswer procedures from the
previous example. However, these procedures will not be tied directly to but-
tons. Instead, for multiple-choice questions we will add two new procedures,
RightAnswerButton and WrongAnswerButton, that will be tied to the but-
tons with right and wrong answers. Here are the new procedures, together with
the Dim statements and a slightly modified Initialize procedure. Use
GetStarted, YourName, DoingWell, and DoingPoorly procedures from
any earlier example, and use RightAnswer and WrongAnswer procedures
from the previous example (see page 136), along with the following:
Dim numCorrect As Integer
Dim numIncorrect As Integer
Dim userName As String
Dim qAnswered() As Boolean
Dim answer() As String 'Array to store answers
Dim numQuestions As Long
Dim printableSlideNum As Long
Sub Initialize()
Dim i As Long
numCorrect = 0
numIncorrect = 0
printableSlideNum = ActivePresentation.Slides.Count + 1
numQuestions = ActivePresentation.Slides.Count - 2
ReDim qAnswered(numQuestions)
ReDim answer(numQuestions)
For i = 1 To numQuestions
qAnswered(i) = False
Next i
End Sub
thisQuestionNum = _
ActivePresentation.SlideShowWindow.View.Slide.SlideIndex - 1
answer(thisQuestionNum) = answerButton.TextFrame.TextRange.Text
RightAnswer
End Sub
140 More Tricks for Your Scripting Bag
thisQuestionNum = _
ActivePresentation.SlideShowWindow.View.Slide.SlideIndex - 1
answer(thisQuestionNum) = answerButton.TextFrame.TextRange.Text
WrongAnswer
End Sub
You have already seen (in the RightAnswer and WrongAnswer procedures)
thisQuestionNum used to store the number of the current question. The only
new code is the Dim statement to declare answer as an array and the
answerButton.TextFrame.TextRange.Text to get the text from the but-
ton that was pressed (as described above). In addition, we have done a bit of re-
structuring. In the original example in Chapter 7, each button had its own
procedure, and that procedure took care of storing the answer, keeping track of
which question was answered, and keeping score. We have divided up that
work. Now the RightAnswerButton and WrongAnswerButton procedures
take care of storing the answer, and the RightAnswer and WrongAnswer pro-
cedures take care of keeping track of which question was answered and keeping
score.
This division of labor will be important when we add a short-answer ques-
tion. For short-answer questions, we are going to need a Question procedure
for each question. That procedure will ask the question, judge the answer, and
store the answer. When it figures out if the answer was right or wrong, it will
call the RightAnswer or WrongAnswer procedure. So we need the follow-
ing procedures:
• Each short-answer question needs its own Question procedure
(Question1, Question2, Question3).
• All the multiple-choice questions need one RightAnswerButton
and one WrongAnswerButton procedure, which will be tied to ev-
ery button with a right and wrong answer, respectively.
• All the questions need one RightAnswer and WrongAnswer
procedure, which is called from RightAnswerButton,
WrongAnswerButton, and each Question procedure.
thisQuestionNum = _
ActivePresentation.SlideShowWindow.View.Slide.SlideIndex - 1
Which Button Did I Press? 141
The changes to this procedure from the example in Chapter 7 are simply to ac-
count for the fact that answer is an array now. Nothing else has changed.
The final change to our code comes in the PrintablePage procedure.
You could simply change this procedure to use the array (using answer(1),
answer(2), answer(3), instead of answer1, answer2, answer3), but this
would require you to change the procedure every time you add a new question.
The purpose of complicating our code with arrays was to eliminate any unneces-
sary changing of code. Our new PrintablePage procedure follows:
Sub PrintablePage()
Dim printableSlide As Slide
Dim homeButton As Shape
Dim printButton As Shape
Set printableSlide = _
ActivePresentation.Slides.Add(Index:=printableSlideNum, _
Layout:=ppLayoutText)
printableSlide.Shapes(1).TextFrame.TextRange.Text = _
"Results for " & userName
printableSlide.Shapes(2).TextFrame.TextRange.Text = _
"Your Answers" & Chr$(13)
For i = 1 To numQuestions
printableSlide.Shapes(2).TextFrame.TextRange.Text = _
printableSlide.Shapes(2).TextFrame.TextRange.Text & _
"Question " & i & ": " & answer(i) & Chr$(13)
Next i
printableSlide.Shapes(2).TextFrame.TextRange.Text = _
printableSlide.Shapes(2).TextFrame.TextRange.Text & _
"You got " & numCorrect & " out of " & _
numCorrect + numIncorrect & "." & Chr$(13) & _
"Press the Print Results button to print your answers."
printableSlide.Shapes(2).TextFrame.TextRange.Font.Size = 9
Set homeButton = _
ActivePresentation.Slides(printableSlideNum).Shapes _
.AddShape(msoShapeActionButtonCustom, 0, 0, 150, 50)
homeButton.TextFrame.TextRange.Text = "Start Again"
homeButton.ActionSettings(ppMouseClick).Action = ppActionRunMacro
homeButton.ActionSettings(ppMouseClick).Run = "StartAgain"
Set printButton = _
ActivePresentation.Slides(printableSlideNum).Shapes _
.AddShape(msoShapeActionButtonCustom, 200, 0, 150, 50)
printButton.TextFrame.TextRange.Text = "Print Results"
printButton.ActionSettings(ppMouseClick).Action = ppActionRunMacro
142 More Tricks for Your Scripting Bag
printButton.ActionSettings(ppMouseClick).Run = "PrintResults"
ActivePresentation.SlideShowWindow.View.Next
ActivePresentation.Saved = True
End Sub
Other than using the answer array, the main change to this procedure is that we
must loop through all the answers so we can display them. We cannot put a line
for each answer, as we have done in the past, because we do not know how many
questions we will have. Instead, we use a For loop to cycle through the answers
and add them to the slide:
For i = 1 To numQuestions
printableSlide.Shapes(2).TextFrame.TextRange.Text = _
printableSlide.Shapes(2).TextFrame.TextRange.Text & _
"Question " & i & ": " & answer(i) & Chr$(13)
Next i
In English, this code says: For each answer in the answer array, take all the
text we have already put in Shape2 of the slide (printableSlide.
Shapes(2).TextFrame.TextRange.Text) and add (&) to that the question
number ("Question " & i) and the answer with a new line (answer(i) &
Chr$(13)). After the For loop, we also add to all of that the score and the in-
structions for printing the slide.
Finally, if you are using a version of PowerPoint that does not automati-
cally change the size of the text to fit the text box, you will want to be sure to
change the size of the text so you can fit more than three or four answers on the
slide:
printableSlide.Shapes(2).TextFrame.TextRange.Font.Size = 9
1. For each multiple-choice question, do not touch the VBA; just add the
question slide and tie the button for the right answer to
RightAnswerButton and the buttons for wrong answers to
WrongAnswerButton.
2. For each short-answer question, add a slide with the question and tie
the question button to a new procedure that is exactly like
Question3, except that it will have a different number for the name
of the procedure (Question4, Question5, etc.) and it will change
the text of the question in the InputBox statement and the correct an-
swer(s) to check for in the If statement.
3. If you have a lot of questions, change the font size of the text box in
the PrintablePage procedure to 9 or smaller.
Random Numbers 143
Random Numbers
Random numbers are a powerful tool. Often you know exactly what you
want in your presentation and in exactly what order. At other times you want to
mix things up randomly. For example, you might want to practice addition facts,
but you don’t want to specify every possible combination of one-digit numbers.
Instead you want the computer to randomly generate problems for you. In an-
other example, you might have a large pool of questions, but you only want to
ask a few that are randomly selected. This section explores these examples.
To have the computer generate random numbers, you need to know three
things: Randomize, Rnd, and Int. For you math purists, computers cannot gen-
erate truly random numbers, but they can come close enough for almost any
purpose.
To be sure they are close enough for our purposes, we need to make sure
that they are not the same every time. That is why we start with a Randomize
statement. Just put this somewhere where it will be run before you need any ran-
dom numbers (such as in your Initialize procedure). Imagine that the com-
puter has a big deck of cards with numbers on them. When you ask for a random
number, it picks the first card off the top of the deck and gives you the number on
it. When you ask for another random number, it picks the next card. This deck of
cards starts out in the same order every time, so every time you start the presenta-
tion and ask for a bunch of cards, you will get the same cards. This isn’t very
good. What we need is to shuffle the cards. Randomize shuffles the cards. We
only need to do this once when we run the presentation, because the deck of
cards is very large. That is why we do this in our Initialize procedure.
Next, we want to get a random number. This is done with the Rnd state-
ment. You could have a procedure that includes:
myRandomNumber = Rnd
MsgBox(myRandomNumber)
This will pop up a MsgBox with a random number in it. The problem is that the
number that is generated is somewhere between 0 and 1. Normally, we want ran-
dom numbers that are positive integers (you know: 1, 2, 3, 4, 5, 6, . . . ). Have no
fear. That is where Int comes in. Int takes a real number and chops off every-
thing after the decimal point. For example, Int(3.1415926) returns 3, and
Int(.4567) returns 0. We can generate a random number between 0 and 9
with:
myRandomDigit = Int(10 * Rnd)
upper is the biggest number you would want, and lower is the smallest number
you would want. For our 0 through 9 example, we would have Int((9 – 0 +
1) * Rnd + 0) or Int(10 * Rnd) + 0) or just Int(10 * Rnd). If we
wanted numbers from 1 to 100, we would have Int((100 – 1 + 1) * Rnd +
1) or Int(100 * Rnd + 1). If we wanted numbers from 50 to 100, we would
have Int((100 – 50 + 1) * Rnd + 50) or Int(51 * Rnd + 50). Don’t
worry if you don’t quite understand the math; just use the simple formula, and
you will be fine.
Sub Initialize()
Randomize
End Sub
Sub RandomQuestion()
Dim first As Integer
Dim second As Integer
first = Int(10 * Rnd)
second = Int(10 * Rnd)
answer = InputBox("What is " & first & " + " & second & "?")
If answer = first + second Then
DoingWell
Else
DoingPoorly
End If
End Sub
Sub DoingWell()
MsgBox ("Good job")
End Sub
Sub DoingPoorly()
MsgBox ("Try to do better")
End Sub
Keeping Score
With some minor modifications, we can plug RandomQuestion into some
of our other quizzes from Chapter 7. We’ll start by keeping score. Start with the
code from “Keeping Score” in Chapter 7 (see Figure 7.1, page 93). Add the fol-
lowing RandomQuestion procedure (this is the same as the previous
RandomQuestion procedure, except that it calls RightAnswer and
WrongAnswer instead of DoingWell and DoingPoorly):
Sub RandomQuestion()
Dim first As Integer
Dim second As Integer
first = Int(10 * Rnd)
second = Int(10 * Rnd)
answer = InputBox("What is " & first & " + " & second & "?")
If answer = first + second Then
RightAnswer
Else
WrongAnswer
End If
End Sub
Add Ran dom ize to the Ini tial ize pro ce dure. Remove
ActivePresentation.SlideShowWindow.View.Next from RightAnswer
and WrongAnswer so it does not automatically advance to the next slide.
For this to work properly, you need three slides: a title slide, a question
slide, and a feedback slide. The title slide has a button tied to GetStarted. The
question slide has a button tied to RandomQuestion and a button that goes to
the next card. And the feedback slide has a button tied to Feedback.
If you are adventurous, you might try to eliminate the feedback slide and
keep a running total in a text box on the slide. After each question, update the
text in the text box. You already have the number of correct and incorrect an-
swers stored in numCorrect and numIncorrect. You simply need to use this
to update a text box after each question is answered.
146 More Tricks for Your Scripting Bag
done = False
first = Int(10 * Rnd)
second = Int(10 * Rnd)
While Not done
answer = InputBox("What is " & first & " + " & second & "?")
If answer = first + second Then
RightAnswer
done = True
Else
WrongAnswer
End If
Wend
End Sub
This uses a While loop similar to what is used for short-answer questions. The
random numbers are generated before the While loop so that the same question
is asked over and over again until it is answered correctly.
If you want to try to create a printable page with the results, you can try that
on your own. Start with the version of that from this chapter in “Arrays.” Keep in
mind that simply listing the answers might not be helpful because the questions
are randomly generated. You might want to add another array to keep track of
the questions so you can add the questions and answers to your slide.
Figure 8.2. VBA Code for Selecting Five Questions from a Pool of Questions
This presentation consists of a title slide, a last slide, and as many question
slides as we want. The title slide has a button that is tied to the GetStarted pro-
cedure. The question slides have buttons for right and wrong answers that are
tied to the RightAnswer and WrongAnswer procedures, respectively. The last
slide has a button that is hyperlinked to the first slide (no VBA) and plays the ap-
plause sound. This version does not keep score.
148 More Tricks for Your Scripting Bag
The key elements of this presentation are the array visited and the proce-
dure RandomNext. visited has an element for each question. Actually, it has
an element for each slide, but the first and last elements are ignored. The ele-
ments are each set to False in Initialize. When a question is answered cor-
rectly, the element of visited for that question is set to True in the
RightAnswer procedure. In addition, one is added to numRead, a variable that
keeps track of how many questions have been read.
RandomNext is used to go to the next question instead of
ActivePresentation.SlideShowWindow.View.Next. In the past, the
next question has always been the next slide. Now, we want to randomly select a
slide, so we can’t simply go to the next slide. RandomNext first checks to see
whether we have answered five or more questions. Just in case the presentation
doesn’t have five questions, it also checks to be sure we haven’t answered as
many questions as there are:
If numRead >= numWanted Or numRead >= numSlides - 2 Then
numWanted was set in Initialize to be 5; that is, we want to ask five ques-
tions at a time. You can change that number in Initialize if you want to ask
more or fewer than five questions at a time, or you can ask the user how many
questions to do (see below).
If we have asked enough questions, RandomNext jumps to the last slide.
Otherwise, it randomly picks a new slide to jump to. Randomly picking another
slide is very easy using Rnd, but we want to make sure we are jumping to a slide
that we haven’t seen yet. First we randomly pick a slide:
nextSlide = Int((numSlides - 2) * Rnd + 2)
This assigns the randomly chosen slide to nextSlide. The While loop keeps
looping as long as we have seen the chosen slide (visited(nextSlide) =
True). That is, if we pick slide 7 as our next slide, visited(7) will be True if
we have seen slide 7, so we will keep looping, and pick another slide with
nextSlide = Int((numSlides - 2) * Rnd + 2). Once we have picked the
next slide, we can go there with:
ActivePresentation.SlideShowWindow.View.GotoSlide (nextSlide)
That is all you need to choose a few questions from a pool of questions. To add
more questions, you don’t have to change any VBA at all; just add more question
slides between the first and last slide. If you want to ask a different number of
questions, you can either change numWanted = 5 to another number in the
Initialize procedure, or you can try out the code in the next section.
This is a good place to remind you that you can and should use all the tradi-
tional PowerPoint tools at your disposal. For many of the questions I have made
Choose Questions Randomly from a Pool 149
for my daughter, I include pictures from clip art for the answers instead of regu-
lar buttons. I also use sounds liberally. The most important use of sound (aside
from the applause at the end) is sound for difficult words or sentences. If I in-
clude a word or sentence that might be beyond my daughter’s skills, I add a re-
corded sound of me reading the word or sentence. She knows that she can click
on any speaker icon to have something read to her. While I am not a big fan of
bells and whistles, you should use as many traditional features of PowerPoint as
you think are appropriate.
The heart of this procedure is the InputBox statement. That is really all that is
needed. However, my daughter might be inclined to type a very large number
and get a lot of questions (so she can put off going to bed). The While simply
checks to make sure the number chosen is between 1 and 10 inclusive. If you
don’t care what number is chosen, leave out the While loop. If you want to al-
low a different range of numbers, change the numbers in the While statement.
Keeping Score
For my daughter at the age of five, I don’t keep score, but you might want to
report a score at the end. Adding scorekeeping is not hard. We will need
numCorrect and numIncorrect to be declared (Dim numCorrect and Dim
numIncorrect) at the beginning of the module and initialized in the Ini-
tialize procedure (numCorrect = 0 and numIncorrect = 0), just like in
any example that keeps score. Because we are asked to repeat a question until it
is correct, we need qAnswered to be declared Dim qAnswered at the beginning
of the module and initialized in the Initialize procedure (qAnswered =
False). Finally, RightAnswer and WrongAnswer need to adjust the score if
the question has been answered:
150 More Tricks for Your Scripting Bag
Sub RightAnswer()
If qAnswered = False Then
numCorrect = numCorrect + 1
End If
qAnswered = False
DoingWell
visited(ActivePresentation.SlideShowWindow.View.Slide.SlideIndex) _
= True
numRead = numRead + 1
RandomNext
End Sub
Sub WrongAnswer()
If qAnswered = False Then
numIncorrect = numIncorrect + 1
End If
qAnswered = True
DoingPoorly
End Sub
These are all the same changes that we made when we wanted to keep score in
Chapter 7. You should be able to add short-answer questions by using the same
Question procedures for each question that you used in Chapter 7.
You now have a powerful tool for randomly selecting slides. Note that
these examples used quizzes, but if you understand this code, you can do some-
thing very similar to create a random story that picks random slides to go to next.
The heart of this is RandomNext as well as the line:
visited(ActivePresentation.SlideShowWindow.View.Slide.SlideIndex) = True
Together, these will pick a random slide to go to next and mark that you have
gone to that slide.
Conclusion
In this chapter you have developed a better understanding of a few VBA
tricks we had already used, such as looping and If statements, and you learned
several new tricks, including timed functions, arrays, and random numbers.
These tricks are beginning to get more complicated than the earlier chapters, so
if you don’t understand how they work, you can simply type in the VBA code
from the examples. If you do understand how they work, you can think of new
things that you can do with these tricks—or at least modify the examples to suit
your own purposes.
Now that you might be writing some of your own code, or at least typing in
long examples, you have a lot of opportunity to make mistakes. Mistakes are
common in scripting and programming, and they are called bugs. Fixing mis-
takes is called debugging. In the next chapter, you will learn some tricks to help
you debug your code, that is, fix your mistakes.
Exercises to Try 151
Exercises to Try
Ä Create a template of a multiple-choice quiz using the code from
this chapter. Teach three of your friends, colleagues, or students
to create their own multiple-choice quizzes using your template.
Remember that they don’t have to change any of the VBA to do
this.
Ä Create a template of a quiz with short-answer questions using
the code from this chapter. Teach three of your friends, col-
leagues, or students to create their own quizzes with short-an-
swer questions using your template. Remember that they will
have to edit the VBA, so you will have to teach them how to get
to the VBA Editor, but they will only have to copy and paste
your Question code and change the question number, the text
of the question, and the answer to the question in VBA.
9
Debugging Tips
Introduction
In Chapter 8 you added to your bag of tricks. Whether you are ready to ven-
ture out on your own, writing scripts that are more than minor modifications of
the examples in this book, or are simply copying more and more complex exam-
ples, you are bound to make mistakes. This chapter describes several ways to
track down your mistakes and avoid making mistakes in the first place, and
points you to some common mistakes for which you can look when your code
seems like it should work, but it doesn’t.
Vocabulary
• Bug • Debug
• Capitalization • Indenting
• Compile error • Run time error
• Commenting out
The process of fixing bugs is called debugging. If you follow the examples
in this book exactly, debugging is not difficult; you simply compare what you
typed to the example and find the difference. Once you get a little more adven-
turous and try to make a few small changes to the scripts, you will need some
ideas to help you solve problems.
notice that a problem exists. If you are not paying close attention, you will see a
MsgBox pop up, but you will not notice that anything is wrong.
As our procedures become more and more complicated and more and more
interdependent, spotting a problem can be very difficult. If a procedure isn’t tied to a
button but called from another procedure, you can’t simply tie the procedure to a
button and expect it to work. A procedure that depends on other things happening
first is hard to test. If you tie DoingWell to a button and click on the button, you
might not get the results you expect, but it might be because something is wrong, or
it might be because you haven’t clicked on a button that is tied to YourName yet.
This could be because some of your procedures are written incorrectly, you are test-
ing out an isolated procedure before putting the whole presentation together, or you
didn’t force the student to type a name before moving through the presentation.
This is an example of why thoroughly testing your procedures is very im-
portant. If you create a presentation, you know what you are supposed to do. If
you always do what you are supposed to do and everything works, you know the
project works when your students always do what they are supposed to do. Do
your students always do what they are supposed to do? Of course not. They will
get answers wrong. They will click on one button when you gave them direc-
tions to click on another button first. They will use arrow keys and the space bar
to move to the next slide if you forgot to put your presentation in Kiosk mode.
They will click the same button fifty times in a row, just to hear the sound that
the wrong-answer buttons make. In short, they will not do everything right, and
when you are testing your program, you should not either.
errors to turn red by clicking on any other line in your module. Keep in mind that
lines that end with an underscore are continued on the next line, so you have to
hit Enter after the whole line is finished, or you have to click on a different line to
get the error to turn red.
One common mistake is to type a line and immediately switch back to
PowerPoint to test out your procedure. If you do this without hitting Enter or
clicking on another line, you will miss the red, and your procedure will not work.
The line still will be red when you get back to the VBA Editor, but you will have
wasted the time going back to PowerPoint, running your procedure, and scratch-
ing your head for a few seconds while trying to figure out what went wrong.
Usually, with errors that turn red, you will also get a message right away
that tells you something about the error. For example, Figure 9.1 shows a typical
error.
This is a compile error. A compile error happens when the computer can’t even
figure out what to try to do. In this case, it is probably looking for a close paren-
thesis. It even suggests that that might be the case. A line like the following will
generate the error in Figure 9.1:
MsgBox ("hello"
Sometimes these messages are helpful, and sometimes they are not. Al-
though the message in Figure 9.1 indicates that we are missing a comma or a
close parenthesis, sometimes a message like that is the result of some completely
different problem.
Try typing the following procedure to add a 16-point star to your current
slide:
Sub AddStar()
ActivePresentation.SlideShowWindow.View.Slide.Shapes.AddShape _
(msoShape16pointStar
End Sub
The Error in Red 157
If you hit Enter (or click anywhere else in your module) after typing
msoShape16pointStar, you will get the error in Figure 9.1, and the line with
the error will turn red. In this case, we are missing the close parenthesis, so we
can add it:
Sub AddStar()
ActivePresentation.SlideShowWindow.View.Slide.Shapes.AddShape _
(msoShape16pointStar)
End Sub
Now when you hit Enter, the line doesn’t turn red. Does that mean that it works?
No, it does not. But we’re ready to try it out to see if it works.
Create a button and tie it to the procedure AddStar. Go to Slide Show
View and click on your button. No news is bad news. The VBA Editor (or more
accurately, the VBA compiler) couldn’t find anything wrong as you typed, but
when VBA tried to run the procedure, it couldn’t figure it out, so it just gave up.
Unfortunately, we don’t have any more clues as to what is wrong. How-
ever, since we are adding a shape, we might remember that we need to tell VBA
where the shape should go and how big it should be:
Sub AddStar()
ActivePresentation.SlideShowWindow.View.Slide.Shapes.AddShape _
(msoShape16pointStar, 100, 100, 100, 100)
End Sub
We have told VBA that we want our shape to be 100 pixels from the left of
the screen, 100 pixels from the top of the screen, 100 pixels wide, and 100 pixels
tall. This should fully define our shape. Hit Enter and now VBA starts to com-
plain again with the error in Figure 9.2.
Now, VBA thinks we are missing an equals sign. This is a good example of
a cryptic message that can be a bit deceiving. In fact, we are missing an equals
sign, but simply adding an equals sign (like we added a parenthesis earlier)
won’t do the trick. The problem here (as is often the problem when VBA com-
plains about a missing equals sign) is that we have created an object, and when
VBA creates an object, it wants to put that object in a variable (whether or not we
158 Debugging Tips
ever want to do anything with that object again). Thus, we need to set a variable
to point to the new object (using Set because it is an object):
Sub AddStar()
Set myShape = _
ActivePresentation.SlideShowWindow.View.Slide.Shapes.AddShape _
(msoShape16pointStar, 100, 100, 100, 100)
End Sub
Now, we are in good shape! If you hit Enter, nothing will turn red, but we
won’t know if it works until we try it. Go back to PowerPoint, go to Slide Show
View, and click on your button. If all goes well, you will now have a new shape
on your slide.
Of course, if you click on the button a second time, nothing will happen. Or,
it will appear that nothing happens. That is because you will create another shape
on top of the first shape. If you go back into Edit View in PowerPoint, you can
see that you have two shapes by dragging one of the shapes out of the way.
When you run the procedure, if you don’t even get a message that pops up
to say, “Entering the procedure AddStar,” you know the problem probably is not
in the procedure (unless it is in the Dim statements in the procedure because the
I’m Not Seeing Red, But I’m Seeing Red 159
first MsgBox has to come after the procedure’s Dim statements). It could be that
you linked your button to the wrong procedure or, in a more complicated script,
it could be that the problem is in another procedure that calls this one. If you get
the message, you know you have gotten into the procedure. Now, you can add
some more MsgBox commands to try to locate the problem. For example:
Sub AddStar()
Dim myShape As Shape
Try running the above procedure. See if you can find the error. As you run
the procedure, you should get the messages:
• Entering the procedure AddStar.
• I just added the shape, and I’m about to add some text.
• I just added some text, and I’m about to change the color.
But that will be it. You will know that the problem is probably in the fol-
lowing line. If you look closely, you will see that the line has a small typo; it uses
mShape instead of myShape. Once the problem is fixed, try it out again. If it
works, you can delete all the MsgBox lines.
You can also use a MsgBox to tell you what is in a variable. For example,
if something is wrong with the scoring in a quiz, you might want to use the fol-
lowing line at various places to get updates about what the computer thinks the
score is:
MsgBox ("The value of numCorrect is " & numCorrect)
This will work most of the time. Unfortunately, certain kinds of errors will
not turn red and will not allow the procedure to run at all (for example, instead of
misspelling myShape, try misspelling RGB). These are harder to find and are a
good reason to use some tricks to prevent errors in the first place (see “An Ounce
of Prevention”).
160 Debugging Tips
Commenting Out
Because the MsgBox method, in the previous section, works sometimes and
doesn’t work other times, you might need another old programmer’s trick to
find your error: commenting out. Remember that everything on a VBA line after
a single quote is ignored; that is, it is a comment. You can put a single quote at
the beginning of a line and that entire line will be ignored. This is better than de-
leting the line because you still have the code there, and you can get it to run
again by deleting the single quote. Note that the VBA Editor turns comments
green, so if you have anything that is green in your code, it is ignored by VBA.
Sub AddStar()
Dim myShape As Shape
The above procedure is similar to the one earlier, except there is a different
error. If you try running the procedure with this error, nothing will happen. You
won’t even get “Entering the procedure AddStar.” That means that it is time to
comment out some lines to try to track down the problem. Since nothing can
work until the shape is created, you probably want to start with the line after Set
myShape . . . .
Sub AddStar()
Dim myShape As Shape
You’ll notice that all the lines after the Set myShape (except End Sub) line are
green in the VBA Editor. These lines will not run. As far as VBA is concerned,
they are not even there.
Try running the procedure with all the comments. If it works, start remov-
ing the comments (just the single quotes, not the whole lines) from the line be-
low Set myShape. Run it again. If it works, remove the comment from the next
line and run it again. Keep removing one comment and running it again until it
stops working. When it stops working, you have found the problem line. It must
be the last line from which you removed the comment. If you have removed all
the comments and it still doesn’t work, then the problem is probably the Dim
statement or the Set myShape line.
If you go through this exercise, you’ll find that the problem is with the Set
myShape line. mso16PointStar should be msoShape16PointStar. Often
the parameters of procedures are the kinds of errors that will cause a procedure to
not work at all, rather than work until it reaches an error. But the best way to
eliminate errors is to practice some prevention techniques. They won’t prevent
all errors, but they will cut down on errors.
Debugger
The VBA Editor comes with a debugger. In some cases, this will be useful,
but it will not work well for most of our code. The debugger lets you set break-
points to stop your code at certain points as it runs. Unfortunately, this does not
work well for code that runs in Slide Show View, so it is not useful for most of
our purposes.
An Ounce of Prevention
As you write your code, you can use several techniques to help you catch
bugs as you type. These techniques will not prevent all bugs, but they will cut
down on the number you have to find later. If you are perfect and never make
mistakes, these techniques won’t affect anything. The techniques are for human
eyes; the computer will be able to run your code without them. But for those of
us who are not perfect, our human eyes need all the help we can get to catch bugs
or prevent them from happening.
Capitalization
You might have looked at some of the examples and wondered why certain
things were capitalized in certain ways. Some of it is part of the technique to pre-
vent bugs, and some of it is forced upon you by VBA. There are five kinds of
things you can type into the VBA Editor:
1. Comments
2. Text between quotes
3. Variable names
4. Procedure names
5. VBA stuff (built-in function names, procedure names, object names,
etc.)
Comments can be capitalized any way that you like because they are for
you to read. Pay close attention to capitalization of text between quotes because
that will usually be displayed for your students, but for the purposes of debug-
ging, it doesn’t matter how you capitalize it. Capitalization of the last three items
can be important for debugging.
In this book, I have used the following convention: Variable names begin
with a lowercase letter; and procedure names begin with an uppercase letter.
Furthermore, since variable names and procedure names cannot contain spaces,
any new word in the name begins with an uppercase letter. This is a convention,
a technique, a trick. I could have used yourName instead of YourName and
UserName instead of userName. It would have worked fine. However, if you
use this convention, you can look at your code and always tell whether a name
An Ounce of Prevention 163
When you hit Enter, the VBA Editor will change it to:
ActivePresentation.SlideShowWindow.View.Next
The power of this is apparent when you type something wrong. If you left
out a “t” in ActivePresentation, for example, that would not be capitalized.
For example, type the following:
activepresenation.slideshowwindow.view.next
164 Debugging Tips
Indenting
You might have noticed that throughout the text, code examples were in-
dented in a very specific way. Indenting helps you read the code. The computer
will understand your code just fine without indenting, but you are more likely to
make mistakes without it. “Conditionals” in Chapter 8 discussed indenting briefly
because indenting is very helpful for reading If statements. It is also helpful for
reading loops. The more complex the code, the more helpful indenting is.
You can use your own style for indenting, but whatever you decide, you
should stick with it. The easiest way to indent in the VBA Editor is to use the Tab
key. When you hit Tab at the beginning of a line, the line will be indented once.
When you hit Enter to go to the next line, the next line will be indented at the
same level. If you don’t want it indented, simply hit the Backspace key (Delete
on a Macintosh) or hold down the Shift key and hit Tab (shift-Tab). If you have a
block of lines that you want to indent, you can highlight them and hit Tab (or
shift-Tab if you want to un-indent them).
In this book, I have indented three kinds of statements:
Indenting helps you see that something is a part of something else: A group of
lines is part of the Sub, a group of lines is part of the ElseIf portion of an If block,
a continued line is a part of the previous line, etc. Look at the following example:
Sub NestedIf()
If gradeNum > 90 Then
MsgBox ("Great job. You got an A.")
If gradeNum = 100 Then
MsgBox ("You are perfect.")
End If
ElseIf gradeNum > 80 Then
MsgBox ("Good work. B is a very good grade.")
ElseIf gradeNum > 70 Then
MsgBox ("Not bad. C is still passing.")
If gradeNum < 72 Then
MsgBox ("That was close. You were lucky to get a C.")
End If
Else
MsgBox ("You can do better than this.")
End If
If gradNum > 70 Then
MsgBox ("You have passed this class.")
End If
End Sub
You might be able to understand this code, but without indenting, it is hard to tell
which End If goes with which If and under what circumstances each line will
get executed. This is much easier to understand when everything is indented:
Sub NestedIf()
If gradeNum > 90 Then
MsgBox ("Great job. You got an A.")
If gradeNum = 100 Then
MsgBox ("You are perfect.")
End If
ElseIf gradeNum > 80 Then
MsgBox ("Good work. B is a very good grade.")
ElseIf gradeNum > 70 Then
MsgBox ("Not bad. C is still passing.")
If gradeNum < 72 Then
MsgBox ("That was close. You were lucky to get a C.")
End If
Else
MsgBox ("You can do better than this.")
End If
If gradNum > 70 Then
MsgBox ("You have passed this class.")
End If
End Sub
166 Debugging Tips
Each part that is indented is now clearly part of the line before it. It is easiest
to indent and un-indent as you go because as you type your code, you know what
you mean.
In this case the scrollable window gives you a list of all the things you can
type after ActivePresentation. You can choose from the list by dou-
ble-clicking on any item, or you can start typing. As you type, the window high-
lights the first thing in the list (in alphabetical order) that matches what you type.
If nothing is highlighted, you have typed something wrong. Generally, that list is
all that is available to type. If the list of choices has gone away, you can delete
the line back to the dot; when you type the dot again, the list will come back.
In addition, in Windows the VBA Editor will make some suggestions for
parameters for procedures. For example, if you type
activepresentation.slideshowwindow.view.gotoslide(
the VBA editor will give you some hints about what you can type next, specifi-
cally what parameters the GotoSlide method wants (see Figure 9.4).
Figure 9.4. VBA Editor Suggests Parameters for the GotoSlide Method
The little box has a lot of details that will help you. First, you can see that there
are two possible parameters separated by commas: Index and ResetSlide.
Although the box does not tell you what the parameters are for, it does tell you
Hints from the VBA Editor 167
what kind of information they need. In this case, Index is a Long variable
(that’s a kind of integer). You can probably figure out that it is the slide number
of the slide to go to. ResetSlide is an MsoTriState variable (which is usu-
ally just a True or False value).
You should also notice that Index is not in square brackets, but
ResetSlide is. This tells us that Index is required and ResetSlide is not.
That is, you have to tell GotoSlide which slide to go to, but you don’t have to
tell it whether or not to reset (the ResetSlide tells it whether or not to reset the
animation effects on the slide; i.e., leave them in their final state or put them back
at the beginning state). Also, notice that ResetSlide has a default value. That
is, if you don’t include a value for ResetSlide, it will assume you wanted
msoTrue (which is basically the same as True), which means that the slide will
be reset. Finally, you will notice that Index is in bold. That means that the next
thing I type will be the value used for Index. If I type a number and then a
comma, ResetSlide will become bold, meaning that the next value I type will
be the value for ResetSlide. If you type parameters in order, you can just type
the values as in the following:
ActivePresentation.SlideShowWindow.View.GotoSlide(5,True)
If you don’t type them in order, you can use the parameter name, followed by co-
lon equals sign (:=), followed by the value, as in the following:
ActivePresentation.SlideShowWindow.View.GotoSlide(ResetSlide:=True, _
Index:=5)
This is very helpful for a couple of reasons. First, you don’t always have to
look up which parameters are needed. For example, when adding a shape, I can
never remember which comes first and second: Top and Left or Width and
Height. I don’t need to remember because VBA will tell me, as in Figure 9.5.
Figure 9.5. VBA Editor Suggests Parameters for the AddShape Method
Second, you always know what the procedure expects. If you leave off any re-
quired parameters (such as forgetting to specify Width and Height), it won’t
work.
168 Debugging Tips
VBA Help
While Windows versions of the VBA Editor are better at suggesting things
as you type, Macintosh versions have help that is a bit easier to use. In either ver-
sion of VBA, you can choose one of the selections from the Help menu to search
for a keyword. In the Macintosh version, you can highlight a keyword, object, or
method in your code and hit the Help key on your keyboard. This will bring up
help that is directly related to what you are trying to do.
When you are using help, you can get all the information that pops up on
your screen when you type open parenthesis and VBA suggests parameters. You
should also check out the examples to help you understand what you are doing
better.
Common Bugs
Everyone makes mistakes, and everyone makes their own mistakes. How-
ever, a few mistakes are fairly common. If you can’t track down a bug, you
might look for some of these things. The bugs listed below are particularly tricky
to find because they are not a problem with a specific procedure. If one proce-
dure is not working at all or is giving the wrong results, you can usually find the
bug if you stare at that procedure long enough (or use some of the above tech-
niques to track it down). However, the following bugs cause problems for proce-
dures that are completely correct and might have been working a minute earlier.
No matter how long you stare at a procedure, you won’t find the bug if it is
caused by something outside the procedure.
Multiple Modules
You were warned early in this book that you should have only one module
for each presentation. If you have gotten this far in the book, you have probably
heeded that warning. However, some people get confused and add a second
module. Some things will work with more than one module, and some things
won’t. Check the Project window to be sure that you have only one module. If
you can’t remember how to check the modules in your Project window, look
back at Chapter 4 in “Help! I’ve Lost My Windows.”
Usually, when you add one module, it will be named “Module1.” However,
if you played around with modules or accidentally deleted a module, your mod-
ule might be “Module2” or “Module3.” That is OK as long as there is only one
module, whatever it is named. If you have put code in more than one module, use
cut and paste to move all the code into one module. If you had Dim statements at
the top of each module, be sure you put them all together at the top of your one
module and remove any duplicates.
Common Bugs 169
Duplicate Variables
When we declare our variables at the beginning of a module, we create a
box to put information in, and we give that box a name. What if two boxes have
the same name? That would be a problem, and VBA would not know what to do.
In fact, nothing in your module would work at all. You could have buttons tied to
procedures that have nothing to do with the variable that is declared twice, but
they would not work. Nothing would work.
You might have this problem if you are combining two examples or have a
long list of variables that you declare at the beginning of your module, and you
forgot you already declared a variable. If none of your VBA works, check the
variable declarations at the beginning of the module and delete any duplicate
Dim statements.
Duplicate Procedures
Just like VBA doesn’t know what to do when you have two variables with
the same name, it doesn’t know what to do when you have two procedures with
the same name. You might have been playing around with the examples in this
book and accidentally wrote two YourName procedures. They might be exactly
the same or different, but if they have the same name, nothing will work. Figure
out which procedure does what you want and delete the duplicate. Or, if the two
procedures are really supposed to be doing different things, give one of them a
different name. You might also want to add a comment to explain what each
procedure does.
Conclusion
In this chapter you learned about ways to find bugs, how to fix bugs, and
how to prevent bugs. Now that you have learned a great many VBA tricks and
how to make your code work (or fix it when it doesn’t), you are ready to create
your own projects as well as create templates for your students’ projects. The
next chapter talks about the idea of creating templates that provide the frame-
work of a project for your students so they can fill in the content.
Exercises to Try 171
Exercises to Try
Ä The following code is not indented. What will happen if Ella
types 5? What will happen if anyone else types 5? What will hap-
pen if Ella types 10? What will happen if anyone else types 10?
Try to figure it out without running the code. Type it into the
VBA Editor and indent it properly; see if you come up with a dif-
ferent answer now that it is indented. Run the code to see if you
got the right answer.
Sub HowDoYouFeel()
Dim score As Integer
Dim userName As String
userName = InputBox("What is your name?")
score = InputBox("On a scale of 1 to 10, how do you feel?")
If score > 5 Then
If score > 7 Then
If score > 9 Then
If userName = "Ella" Then
If score > 10 Then
MsgBox ("That’s amazing")
Else
MsgBox ("That’s perfect")
End If
ElseIf score < 6 Then
MsgBox ("That’s middling")
Else
MsgBox ("You’re perfect.")
End If
ElseIf score = 5 Then
MsgBox ("Are you middling?")
Else
MsgBox ("Are you above average?")
End If
ElseIf score = 5 Then
MsgBox ("Right in the middle")
Else
MsgBox ("That’s good")
End If
Else
MsgBox ("Not too good.")
End If
End Sub
172 Debugging Tips
Sub YourName()
userName = InputBox("What is your name?")
End Sub
End Sub
Sub BadProcedure()
YorName
If userName = "Ella" Then
MsgBox ("Hello, big girl.")
ElseIf userName = "Ada"
MsgBox ("Hello, little girl.")
Else
MsgBox ("Hello, " & userName)
End If
End Sub
10
Templates
Introduction
In Chapter 9 you learned the last technical tricks presented in this book and
developed a bag of tricks to help you fix any problems that you might encounter.
Now you are ready to embark on using all the tricks you have learned to make
powerful interactive projects. However, your students might not be ready to
make their own powerful interactive projects. This chapter describes templates,
a tool you can use to do the technical and design work for your students, allow-
ing them to concentrate on the content. With a template, you can use all the VBA
features that you want, and your students can use all those VBA features without
even knowing how to open the VBA Editor. This chapter describes templates
and provides several examples, including a sophisticated example that asks the
user for information and adds a slide with that information.
Vocabulary
• Design Template (.pot) File • Template
designing their own multimedia projects. See, for example, Liu and Hsiao (2001),
Liu and Rutledge (1997), or Lehrer, Erickson, and Connell (1994). While this can
be a powerful educational opportunity, it also can be impractical for a number of
reasons, not the least of which are that it is very time-consuming and that your stu-
dents might lack the technical skills to be successful.
Have no fear. Your students can still get many of the benefits of what you
have learned in this book without having to learn it all (or any of it) themselves.
That is where templates come in. If you design a project from scratch, you have
to decide on the appropriate media, appropriate kinds of information, and appro-
priate organization for your project. In addition, you have to develop the project
(including preparing the media, the PowerPoint slides, the VBA, etc.). A tem-
plate allows you to create some of these things for your students. Templates have
been used to facilitate multimedia creation by professional designers; see, for
example, O’Connor (1991). Agnew, Kellerman, and Meyer discusses the use of
templates with students: “The primary purpose of giving students a template for
their early projects is to allow them to concentrate most of their attention on
achieving academic objectives” (1996, p. 250).
Something as simple as a PowerPoint project about an animal can use a
template. You could tell your students that the presentation should contain four
slides: a title slide, a slide about the animal’s habitat with a picture of the animal,
a slide about what the animal eats, and a slide for citing resources. Those simple
instructions are a rudimentary template. You have designed the organization of
the project for the students.
However, you might go further and actually create the slides for them, giv-
ing your students directions about how to fill in the picture and the text. See Fig-
ure 10.1 for an example.
Although this is not a complex project, it might be a good one for second
graders, for example, who are first being introduced to PowerPoint. This project
does not require VBA or hyperlinks or animations or anything but the most basic
features of PowerPoint. For a class of students who are new to PowerPoint, by
getting them started you can save them hours of computer work and allow them
to concentrate on the content.
As projects become more complex, templates become more powerful. You
might want to introduce your students slowly to advanced features of
PowerPoint, or you might not want to introduce them to some features at all. But
you might want them to take full advantage of these features right away.
In Chapter 8 we saw examples of projects that easily can be turned into tem-
plates. You might want your students to write quizzes with all the features of
VBA that we discussed, but you might not want them to have to deal with VBA.
Using the examples from Chapter 8, you can set up a template with no questions
or a fake question and give your students instructions about how to add slides
and tie the buttons to the appropriate procedures. For the multiple-choice exam-
ples, they don’t need to change the VBA code at all.
As another template example, chapter 7 of Agnew, Kellerman, and Meyer
(1996) discusses a current events project. In this project, each student or group
of students creates a single slide about a current event. The slide contains a brief
paragraph about the event and a button for the citation and photograph of the
event. This project could be done as a template in which the teacher creates all
the parts of the project and the students simply add the pictures, citations, and
news summaries. In the end, all the slides are put together to form a class
collection of current events.
Many topics would work well in a template format. Projects that work es-
pecially well are ones in which you would like the students to include a fixed
body of information, and each student or group includes the same kind of infor-
mation about a different topic. For example, school clubs, U.S. presidents, coun-
tries in Europe, Spanish verbs, and state flags are all topics that lend themselves
well to templates.
To save your presentation as a Design Template, you will have to pay atten-
tion to the “Save as type.” If you choose, “Design Template” as your file type, it
will create a .pot file (see Figure 10.2).
If you save a file as a Design Template, you can edit the template (rather than
a project based on the template) by opening the project from within PowerPoint.
That is, start PowerPoint and choose “Open” from the File menu to open it.
Once you have created a template, either as a .pot file or as a regular
PowerPoint presentation, you might want to set it to be “Read-only.” To do this,
quit out of PowerPoint and click once on the file to select it. If you are in Win-
dows, choose “Properties” from the File menu and check the box labeled
“Read-only.” If you are on a Macintosh, choose “Get Info” from the File menu
and check the box labeled “Locked.” This will prevent the template from being
changed accidentally.
Figure 10.4 shows the complete code for this project. Remember that, be-
cause this is a template, my students do not type any of this code. They simply
fill in the content in the first seven slides.
On the first slide, the secret button (the invisible button in the upper left cor-
ner) is tied to the procedure GoToPartners. This procedure goes to the elev-
enth slide. Normally, this could be done with a traditional hyperlink, but in this
case, the eleventh slide is going to be created with VBA. A traditional hyperlink
cannot link to a slide that does not yet exist. On the last slide, the “Look at Poten-
tial Partners Again” button also is tied to GoToPartners for the same reason.
The only other button that uses VBA is the “Yes” button on the eighth slide.
When users decide they want to work with you, they click on this button to initi-
ate a series of events. This button is tied to the WorkTogether procedure, which
controls this series of events.
Figure 10.4. Pick-A-Partner VBA Code
180 Templates
The WorkTogether procedure calls all the procedures needed to make ev-
erything happen. When I took my first computer course, the instructor told us to
think about what we wanted our program to do and write a top-level procedure to
call other procedures to do it. Then, he suggested that you have finished something
important and you should go have a beer. That is what the WorkTogether pro-
cedure does. Go have a beer (if you are of legal drinking age, not driving, not
pregnant, etc.)! This procedure does all of the following:
• It asks the user to input a name, e-mail address, and project idea
(GetNameEmailIdea).
• It jumps to the tenth slide thanking the user for wanting to work with
you (GoToWorkTogether).
• It creates a new slide that contains the name, e-mail, address, and
project idea (AddWorkTogetherSlide),
• It saves the presentation so the newly added slide becomes part of
the presentation (Save),
Figure 10.5. Example of Slide Created When Someone Has Chosen to Work with You
This slide will be inserted as the eleventh slide. The following line creates
the new slide:
ActivePresentation.Slides.Add index:=11, Layout:=ppLayoutText
The index:=11 ensures that the new slide will always be the eleventh
slide in the presentation. The Layout:=ppLayoutText makes it a standard
text slide with a title and one text area. Note that in earlier chapters parameters
for procedures and built-in functions were always contained in parentheses.
As a general rule, VBA expects something to be returned when the parame-
ters are in parentheses and nothing to be returned when they are not.
ActivePresentation.Slides.Add could return the slide object that it cre-
ates (and we could store that in a variable), but because we left off the parenthe-
ses it does not.
Next, we want to add the appropriate text to the slide: the user’s name in the
title area with a brief message; the user’s e-mail address in the text box; and the
user’s idea (if any) in the text box. The code that adds this follows.
With ActivePresentation.Slides(11)
.Shapes(1).TextFrame.TextRange.Text = userName & _
" is interested in working with you."
.Shapes(2).TextFrame.TextRange.Text = "Email: " & userEmail
With .Shapes(2).TextFrame.TextRange
If userIdea = "" Then .Text = .Text & Chr$(13) & _
"No ideas entered" _
Else .Text = .Text & Chr$(13) & "An idea to ponder: " & userIdea
End With
End With
This uses a couple of With blocks (see Chapter 6) and some fairly simple
text ideas (see also Chapter 6). The .Shapes(1) line sets the text in the title
area of the slide. The .Shapes(2) line puts the email address in the text area of
the slide. Then, the With block (through End With) adds the user’s idea to the
text area, or, if the user has no idea, it adds the text “No ideas entered.” It’s sim-
pler than it looks.
182 Templates
In this procedure, the Set line creates the button and sets myShape to point
to it. msoShapeActionButtonForwardorNext creates it as a button with a
forward-pointing arrow. The first With block sets the action (this is what makes
it go to the next slide) with the line .Action = ppActionNextSlide. The
other lines in the first With block aren’t really necessary but complete the action
features of the button.
The second With block sets colors (specifically Fill and Line colors). If
you are using the default color scheme, this entire With block is unnecessary,
but you can play with the parameters to see how the buttons that are created
change.
The last thing you should note about this procedure is that it was created us-
ing a macro. You can do some things by creating macros by going to the Tools
menu and choosing “Record Macro.” Whatever you do will be placed into a
VBA procedure. This is very good for setting up parameters, such as colors and
shapes and locations. However, a macro created in Edit View will not run prop-
erly in Slide Show View. Therefore, use the macro to guide you in creating
shapes and picking colors, but put those parameters into your own code that will
run in Slide Show View. This requires understanding some complicated con-
cepts, so don’t worry if you don’t get it right away.
Exercises to Try 183
Conclusion
In this chapter, you have learned the power of templates. Sometimes you
want your students to work on technical skills, but technology in the classroom
primarily is a tool for learning the curriculum. As a teacher, you need to balance
the use of technology with the needs of the curriculum. If the technology de-
mands are too great, the curriculum will be lost. Templates are the perfect solu-
tion for many tasks. If you want your students to use powerful technological
features, such as the VBA features of PowerPoint, but you don’t want them to
focus on the technology, you can create a template with all the features they
need, so they can focus on the curriculum but still get the advantage of the
powerful features.
You can use templates with your students with early projects while they are
still getting used to PowerPoint, or you can use templates for all projects. Tem-
plates do not need to include advanced features like VBA. Even the simplest
templates (like the Animal Project in Figure 10.1, page 174) can be used to focus
your students and limit the amount of technology and design they have to
understand.
Exercises to Try
Ä Create a simple presentation (possibly something like the Ani-
mal Project shown in Figure 10.1). Save it as a Design Template.
Quit PowerPoint and double-click on your template. Observe
what happens when you try to save the presentation that is
opened.
Ä Pick one of the projects from earlier chapters in this book (the
quizzes in Chapter 8 work well as templates) and create a tem-
plate for your students. Set it up to include all the VBA that is
needed, all the basic slides that are needed, and instructions for
your students so they know what to do with the project. For ex-
ample, if you choose a quiz format, you can create the title slide,
one question slide, and the feedback slide while giving instruc-
tions for how to add new slides and tie the right and wrong an-
swers to the procedures that you have already included.
Epilogue
Using multimedia that you create and having your students create multime-
dia can have a powerful impact on the curriculum, and it can help students un-
derstand media and gain a level of media literacy. For more information about
media literacy, look for the Alliance for a Media Literate America at
http://www.nmec.org/.
Your journey is just beginning. You have the power to improve your stu-
dents’ learning. You have the power to use PowerPoint to engage and interact
with your students. Technology is not always easy to use, but if you have come
this far, you have mastered another piece of powerful technology to help your
students learn. Don’t stop here. Create exciting interactive presentations. Have
your students create exciting interactive presentations. Share your successes, get
help with your frustrations, and keep in touch at our Web site, www.lu.com.
References
Data structures, 134 Edit View, 13, 24, 27, 30, 45, 132, 133,
DDD-E Model, 3–5 158, 182
decide, 3–4 Elements of an array. See Arrays
design, 4 Embedded elements, 15, 18. See also
develop, 4 Sounds, inserting; Pictures,
evaluate, 3–4 inserting
Debugger, 162 Empty string, 56, 82
Debugging, 150, 153–172 End Sub, 42, 162
commenting out, 160–161 Equal sign (=). See Assignment operator
compiling, 161 Error messages, 154, 155, 156, 157
with MsgBox, 158–159 Errors. See Bugs; Debugging
Decide. See DDD-E Model compile, 156–158, 161
Declaring. See Dim preventing, 159
Delay. See Timing capitalization, 162–164. See also
Deleting slides, 108 Capitalization
Design, 1, 2–11. See also DDD-E indenting, 164–166. See also
Model Indenting
Design Template (.pot) File. See File red, 155–158, 161
types, Design Template (.pot) run time, 161
Develop. See DDD-E Model testing for, 154–155
Dialog box Escape key, 29, 30, 45, 126
Action Settings, 26, 28, 29, 44–45, Evaluate. See also DDD-E Model;
46 Evaluation
Custom Animation, 71, 72 Evaluation, 4–5
Do you like chocolate?, 67 formative, 4
enable macros, 38 summative, 4–5
Hello, 42 Examples
Insert Hyperlink, 22–23 Animal Project template, 174
Macro Security, 38–39 interactive story, 80–81, 150
mystery, 85–89
Index 191