SPSS Macros

SPSS macros are fundamentally a form of string manipulation.

See also Macro String Functions and Macro Arithmetic for documentation on specialized use of macros.


Arguments

Arguments can be passed into a macro. Be mindful that they will first be tokenized before being exposed to the macro expansion.

Function

Behavior

!tokens(N)

Consume N tokens

!charend('C')

Consume all tokens until C

!enclose('S','E')

Consume all tokens starting from S until E

!cmdend

Consume all tokens until the end of the command

Named Arguments

Tokens can be set into named arguments using a key = function pattern.

define !generate(var1=!tokens(1)
                /var2=!tokens(1))
  compute !var1=0.
  compute !var2=0.
!enddefine.

!generate var1=foo var2=bar.
!generate var2=bar var1=foo.

Note that the arguments are accessed in the program by prepending the name with an exclamation mark (!).

Also note that arguments can be specified in any order.

Positional Arguments

Tokens can also be set into positional indices (!1, !2, and so on) using the !POSITIONAL keyword.

define !generate(!positional !tokens(1)
                /!positional !tokens(1))
  compute !1=0.
  compute !2=0.
!enddefine.

!generate foo bar.

All positional arguments can be accessed as a blank-delimited string with !*.

Defaults


Conditional Processing

The !IF ... !THEN ... !IFEND syntax is used for conditional processing inside a macro. Additional conditions can be expressed with !IF !ELSE or !ELSE.

define !export(type = !tokens(1))
  !IF (!type !EQ "xlsx") !THEN
    save translate /outfile="export.xlsx" /type=xlsx /version=12 /map /replace /fieldnames /cells=values.
  !ELSE !IF (!type !EQ "dta") !THEN
    save translate /outfile="export.dta" /type=stata /version=8 /edition=se /map /replace.
  !ELSE
    save outfile="export.sav".
  !IFEND
!enddefine

Inside the !IF construct, string literals can be left unquoted. This comes with the unexpected side-effect of case-sensitivity.

Operators

The following operators are valid inside conditions.

Operator

!EQ, =

!NE, ~=

!GT, >

!GE, >=

!LT, <

!LE, <=

!OR, |

!AND, &

!NOT, ~


Loops

Ranges

define !per_year(var = !tokens(1)
                /timevar = !tokens(1)
                /start = !tokens(1)
                /end = !tokens(1))
  !DO !y = !start !TO !end !BY 1
    temporary.
    select if !timevar=!y.
    frequencies /variables=!var.
    execute.
  !DOEND
!enddefine

!per_year var=population timevar=year start=2000 end=2008.

Iteration

define !each_year(var = !tokens(1)
                 /timevar = !tokens(1)
                 /years = !cmdend)
  !DO !y !IN (!years)
    temporary.
    select if !timevar=!y.
    frequencies /variables=!var.
    execute.
  !DOEND
!enddefine

!each_year var=population timevar=year years=2000 2002 2008.


CategoryRicottone