TOPIC: X MACRO
Fixing CALL EXECUTE Macro Variable Resolution and Macro Execution Timing in SAS
A recent run of SAS macro writing has seen me save some effort by using CALL EXECUTE within data steps. This goes well when everything is dataset-based since you are using the loop that is at the heart of data step processing. Things need more need when you start mixing in macro variables and macro calls because CALL EXECUTE blocks usually execute at the step boundary, which is not when macro processing takes place.
That is because the macro processor acts before the compilation and execution of normal SAS code, which makes sense because this is a form of metaprogramming. After all, SAS Macro builds up code to be compiled and executed; this happens in one sequence making the process feel like script interpretation and execution to a user. With CALL EXECUTE, this has the consequence of calling an executing a macro out of sequence with the inputs that it needs to complete successfully. Thus, the code below will fail to do that.
data _null_;
line = cat("data x; a= ", var1 ,"; run;";)
call execute(line);
line = cat("%macro1(invar=", var2, ")");
call execute(line);
run;
The solution to this sequencing issue is to enclose any macro variables and calls in single quotes within CALL EXECUTE function input to delay macro processing (usually, you use double quotes to ensure that macro code is resolved but not here). Making that change turns the code above into what follows below:
data _null_;
line = cat("data x; a= ", var1 ,"; run;";)
call execute(line);
line = cat('%macro1(invar=', var2, ')');
call execute(line);
run;
Then, everything works in the expected sequence to give the expected results and without issuing confusing errors and warnings to the SAS log. While it took a search to find it, SAS does have documentation showing how to accomplish this sort of thing, which helps when understanding what is happening and what is needed.