
Adobe InDesign CS4 Scripting Tutorial
Scripting and the InDesign object model
13
VBScript
Rem To convert from a number to a string:
myNumber = 2
myString = cstr(myNumber)
Rem To convert from a string to an integer:
myString = "2"
myNumber = cInt(myString)
Rem If your string contains a decimal value, use "cDbl" rather than "cInt":
myNumber = cDbl(myString)
Variables
A
variable
is a container for a value. They are called “variables” because the values they contain might
change. A variable might hold a number, a string of text, or a reference to an InDesign object. Variables
have names, and you refer to a variable by its name. To put a value into a variable, you
assign
the data to
the variable.
In our first sample script, above, we used the variables
myDocument
and
myTextFrame
to avoid having to
provide the full specification of the object (such as
text
frame
1
of
page
1
of
document
1
or
app.documents.item(0).pages.item(0).textFrames.item(0)
) every time we refer to the object.
In all the sample and tutorial scripts that come with InDesign, all variables start with
my
. This way, you can
easily differentiate variables we created in a script from the scripting language terms.
Assigning a value to a variable
Assigning values or strings to variables is fairly simple, as shown in the following table:
N
OTE
:
In JavaScript, all variables not preceded by
var
are considered global by default; that is, they are not
bound to a specific function.
var
is not required, but we recommend you use
var
in any script with more
than one function. In AppleScript and VBScript, variables are local unless specifically defined as global
variables. This means the variables do not persist outside the function in which they are created.
Try to use descriptive names for your variables, like
firstPage
or
corporateLogo
, rather than
x
or
c
. This
makes your script easier to read. Longer names do not affect the execution speed of the script.
Variable names must be one word, but you can use internal capitalization (
myFirstPage
) or underscore
characters (
my_first_page
) to create more readable names. Variable names cannot begin with a number,
and they cannot contain punctuation or quotation marks.
Language
Examples of assigning a value to a variable
AppleScript
set myNumber to 10
set myString to "Hello, World!"
set myTextFrame to make text frame at page 1 of myDocument
JavaScript
var myNumber = 10;
var myString = "Hello, World!";
var myTextFrame = myDocument.pages.item(0).textFrames.add();
VBScript
myNumber = 10
myString = "Hello, World!"
Set myTextFrame = myDocument.Pages.Item(1).TextFrames.Add