Word Hacks [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Word Hacks [Electronic resources] - نسخه متنی

Andrew Savikas

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید







Hack 2 Macros 101: A Crash Course

This hack offers a whirlwind tour of macros,
which can help you automate tedious and time-consuming
tasks.

Word 6 or later lets you write,
record, and play
macros, or short programs that automate tasks in
Word. The term macro comes from macrocommand,
which originally referred to a bunch of commands strung together and
executed all at once. Typically, you would record a sequence of
commands, give the sequence a name, and then play it back as needed.
You can certainly use Word macros for this purpose, but it represents
only the tip of the iceberg.

You create Word macros using Visual Basic for
Applications, usually abbreviated as
VBA. Even recorded macros get translated into
VBA, which you can then examine or edit.

VBA belongs to the BASIC family of computer languages. Compared to
other computer languages, such as C or Java, you may find it easier
to master. But like any language, you'll need to use
it in order to learn it.

A true VBA tutorial falls outside the scope of this book. This hack
simply shows you how to create and run a macro like the ones used in
this book.


For a thorough guide to Word macros, check out Writing Word
Macros (O'Reilly).


1.3.1 Nuts and Bolts


Most of the macros in this book, as well as
any you record within Word, use the subroutine
(Sub) procedure. Each one begins with the
following line:

Sub MacroName

where MacroName is the name of the macro.
Each ends with this line:

End Sub

The instructions you give Word fit between
these two lines. Cooking offers a
useful analogy. In fact, you can think of a macro as a recipe. You
begin with the list of ingredients at the top and then add a sequence
of actions to transform those ingredients into something edible. You
can even split some recipes into several shorter recipesi.e.,
one for the sauce, one for the meatto make them easier to
follow. The same goes for macros. In the example below, note the list
of "ingredients" at the top,
followed by the rest of the code to work those ingredients into the
main course:

Sub CountCommentsByBob( )
Dim oComment As Comment
Dim iCommentCount As Integer
Dim doc As Document
iCommentCount = 0
Set doc = ActiveDocument
For Each oComment In doc.Comments
If oComment.Author = "Bob" Then
iCommentCount = iCommentCount + 1
End If
Next oComment
MsgBox "Bob made: " & iCommentCount & " comments"
End Sub

The next section shows you how to put macros to work in your
documents.


1.3.2 Hello, World


A tradition in computer
books is to present the first example as
a simple program that announces its existence to the world. In Word
VBA, that would go something like this:

Sub HelloWorld
MsgBox "Hello, World"
End Sub

To create this macro, select ToolsMacroMacros to
display the Macros dialog. A listbox at the bottom, labeled
"Macros in," lists all the open
templates and documents where you can store your macro, as shown in
Figure 1-11. For example, choose the
"All active templates and
documents" option to create your macro
in the
Normal.dot template.


Figure 1-11. Choosing where to store a macro

Next, type HelloWorld in the
"Macro name" field and press the
Create button, as shown in Figure 1-12.


Figure 1-12. Creating a new macro from the Macros dialog box

When you press this button, Word does three things:

Within your Normal template, Word creates a new
module to hold your macro code, named
NewMacros.

Word launches the Visual Basic Editor.

Word fills in the first and last lines of the macro for you and
inserts some comments about the macro. (The comments help the people
who read the programs. In VBA, comments always start with a single
quotation mark or apostrophe.)

You will see the shell of your new macro in the Visual Basic Editor,
as shown in Figure 1-13. The Project Explorer,
in the top left,
lists all open documents and templates, including any add-ins (such
as the MSWordXML ToolBox [Hack #92] ).
Notice that the NewMacros module is highlighted in
the Modules section of the Normal template.


Figure 1-13. The Visual Basic Editor

To finish the macro, just put your cursor in the blank line above
End Sub and type the following:

MsgBox "Hello, World!"

Now press the Play button (the green wedge) on the toolbar to run the
macro. You'll see the dialog shown in Figure 1-14.


Figure 1-14. Greetings from your first macro

To create another macro in the same module within the Normal
template, just start a new line after End
Sub and type in the first line for another macro.
You can also paste code from other macros directly into the Visual
Basic Editor.


1.3.3 Organizing and Debugging Your Macros


If you want to create a new module to help organize your macros,
select the template or document where the new module will go from
within the Project Explorer, then select InsertModule. New
modules created like this are always named
Module1, Module2, and so on, as
shown in Figure 1-15. In the Properties window,
located just under the Project Explorer (see Figure 1-13), you can rename the modules.


Figure 1-15. A new module inserted into the Normal template

To help you cut down (or at least easily pinpoint) the number-one
source of program bugstyping errorsyou should always
include the following as the very first line of code in any module:

Option Explicit

This tells Word to make
sure you've
declared every variable you use in the macro. To
continue with the cooking analogy, it's like
checking the recipe to make sure you listed every ingredient at the
top. If you try to run a macro with a misspelled variable name, Word
will warn you and highlight the undeclared variable, as shown in
Figure 1-16.


Figure 1-16. Word can help find mistakes in your macros

Once you finish editing your macro, select FileClose and
Return to Microsoft Word.


1.3.4 Running Macros


To run a macro from
within Word, select
ToolsMacroMacros, select it from the list, and
press the Run button, as shown in Figure 1-17.


Figure 1-17. Running a Macro from within Word

If you frequently use the same macro, you can assign it a toolbar
button or keyboard shortcut. Select ToolsCustomize, click
the Commands tab, and select Macros from the Categories column, as
shown in Figure 1-18. In the Commands column, find
the macro and drag it to a toolbar or menu. After you place the
macro, you can right-click it to change its name or add an image to
its button, as shown in Figure 1-19.


Figure 1-18. Selecting the Macros category from the Customize dialog


Figure 1-19. Changing the name of the button used to activate a macro placed on a toolbar or menu

If you use or create a set of macros that become an integral part of
your workflow, consider separating those into a separate Macros
template [Hack #50]
that will load automatically whenever Word starts.


1.3.5 Getting Help from the Editor


The Visual Basic
Editor is a
full-featured development environment that includes
several features designed to help you write VBA code.

1.3.5.1 IntelliSense


As you type VBA code, the editor will attempt to
complete the statement for you, as shown in Figure 1-20.


Figure 1-20. The Visual Basic Editor can help you write code faster

Though the lists will generally appear automatically as you type, you
can explicitly request a list of items that match the text
you've already typed by pressing Ctrl-spacebar.

1.3.5.2 The Immediate window


In the Immediate window, you can
enter individual statements that are executed immediately. When a
statement is prefaced with a question mark, the return value is
printed to the Immediate window, as shown in Figure 1-21.


Figure 1-21. Using the Immediate window

The Immediate window is a helpful tool for testing out a macro. Type
the following line of code in a macro:

Debug.Print StringToPrint

Replace StringToPrint with a text string
or a string variable you want to keep an eye on, which will be
printed to the Immediate window. This technique is shown in Figure 1-22.

1.3.5.3 Stepping through code


As you test out a macro, it can help to
"step" through it as it runs. Word
will execute one line of the macro, then wait for you to tell it to
run the next line. In this way, you can slow down a macro and better
understand it. If you hover your mouse over a variable while stepping
through the code, Word displays the current contents of the variable
as a ToolTip.

To step through a macro, put your cursor anywhere inside it and press
F8. Each time you press F8, you execute another line of code. The
line that will be executed the next time you press F8 will be
highlighted in yellow, and an arrow will appear at the left, as shown
in Figure 1-22.


Figure 1-22. Using the Visual Basic Editor to step through a macro line by line


1.3.6 Exploring the Word Object Model


In Word VBA, all of Word's
parts are
represented as objects. A document is an object,
a paragraph is an object, and even a font name is an object. All of
these objects are interrelated, and evaluating and manipulating them
is the basis of programming Word with VBA.

To browse the Word object model, select ViewObject Browser
from within the Visual Basic Editor. Using the Object Browser can be
an overwhelming experience for beginners, but it can be a great help
in figuring out how to automate a particular component or task within
Word. The Object Browser is shown in Figure 1-23.


Figure 1-23. Using the VBA Object Browser


/ 162