## Macros

Solved
Occasional Contributor
Posts: 5

# Macros

I am working on a macro

Is this a valid piece of code:

%let year2 = 1 + &year.;

such that all instances of &year2. will have the value of &year. +1?

so if &year. was defined as 5, then wherever &year2. is encountered, it will be a 6?

by the way &year. refers to a variable included in the original macro expression: %macro XX (year);

Accepted Solutions
Solution
‎04-18-2013 05:38 PM
Super User
Posts: 23,733

## Re: Macros

It's valid but not what you want. Look up %eval

40   %let year=5;

41   %let year2=1 + &year.;

42

43   %put NOTE: YEAR = &year;

NOTE: YEAR = 5

44   %put NOTE: YEAR2 = &year2;

NOTE: YEAR2 = 1 + 5

45

46   %let year3=%eval(1+&year.);

47   %put NOTE: YEAR3 = &year3;

NOTE: YEAR3 = 6

All Replies
Solution
‎04-18-2013 05:38 PM
Super User
Posts: 23,733

## Re: Macros

It's valid but not what you want. Look up %eval

40   %let year=5;

41   %let year2=1 + &year.;

42

43   %put NOTE: YEAR = &year;

NOTE: YEAR = 5

44   %put NOTE: YEAR2 = &year2;

NOTE: YEAR2 = 1 + 5

45

46   %let year3=%eval(1+&year.);

47   %put NOTE: YEAR3 = &year3;

NOTE: YEAR3 = 6

Occasional Contributor
Posts: 5

## Re: Macros

okay i will try that

so would this be a valid way of using a macro-defined variable as a counter in a do-loop?

%let x.=%eval(&x.+1);

so if &x. was 5 before this statement, it will now be equal to 6?

thanks

Super Contributor
Posts: 644

## Re: Macros

If you have a loop  %do x = 1 to 9   in a macro, the variable x (ie &x) will be incremented automatically for each pass of the loop.

If you are trying to increment a macro variable in a dataset do loop, it will fail.  Macro statements are evaluated before SAS datasteps run.

You may get an error with   %let x.=%eval(&x.+1);   in open code because the period is not part of the variable name, so   %let x. ... will probably cause a syntax error because of the redundant period.  The period is only required when referencing the macro variable if it is part of a longer contiguous expression, such as &year.Champion, which would resolve as 2013Champion; as distinct from &yearchampion which SAS would interpret as the longer name of another macro variable.  The period in the expression (&x.+1) will not cause an error, but it is not needed.

You should try and get proper training in the use of macros before throwing them into your code.

Richard

🔒 This topic is solved and locked.