SAP ABAP - Macros
If we want to reuse the same set of statements more than once in a program, we need to include them in a macro. For example, a macro can be useful for long calculations or for writing complex WRITE statements. We can only use a macro within a program in which it is defined. Macro definition should occur before the macro is used in the program.
Macros are designed based on placeholders. Placeholder works like pointers in C language. You can define a macro within the DEFINE...END-OF-DEFINITION statement.
Following is the basic syntax of a macro definition −
DEFINE <macro_name>. <statements> END-OF-DEFINITION. ...... <macro_name> [<param1> <param2>....].
It is necessary to define a macro first before invoking it. The <param1>…. replaces the placeholders &1...in the ABAP statements contained in the macro definition.
The maximum number of placeholders in a macro definition is nine. That is, when a program is executed, the SAP system replaces the macro by appropriate statements and the placeholders &1, &2,….&9 are replaced by the parameters param1, param2,....param9. We may invoke a macro within another macro, but not the same macro.
Go to transaction SE38. Create a new program ZMACRO_TEST along with the description in the short text field, and also with appropriate attributes such as Type and Status as shown in the following screenshot −
Following is the code −
REPORT ZMACRO_TEST. DEFINE mac_test. WRITE: 'This is Macro &1'. END-OF-DEFINITION. PARAMETERS: s1 type C as checkbox. PARAMETERS: s2 type C as checkbox. PARAMETERS: s3 type C as checkbox default 'X'. START-OF-SELECTION. IF s1 = 'X'. mac_test 1. ENDIF. IF s2 = 'X'. mac_test 2. ENDIF. IF s3 = 'X'. mac_test 3. ENDIF.
We have 3 checkboxes. While executing the program, let’s select the S2 checkbox.
The above code produces the following output −
A Macro Program This is Macro 2
If all checkboxes are selected, the code produces the following output −
A Macro Program This is Macro 1 This is Macro 2 This is Macro 3