SAP resource site

Function modules form a very important part in Modularization of the code. They are used to reduce the redundancy of code , improves debugging and readability of the program. The following tutorial explains in depth how to create your own custom function module(FM) and using it.

That’s it. Now we will create a function module. Same SE37 transaction create a FM zau_getwerks.

Give function group name we just created and give a short text for the FM

We are creating this FM which accepts a material number and gives the plant details for that material.Create a import parameter lv_matnr of type matnr. We can make it pass by value also by checking Pass by value. By default it is pass by reference only. If optional is checked then passing this parameter is not mandatory in the program.

Import Parameters - FM

Here I will create a output table named output which is having a structure of zty_material.Create a zty_material structure from SE11 . Data type >> Create structure and add matnr and werks component to that structure.

Tables in FM

We will add exceptions now. Exceptions provide a easy way for error handling in FMs. We will create 2 FM’sOne FM when we enter invalid material and another when data is not present related to plant.(No data in marc table)

Exceptions in FM

Now the main coding/logic part of the program. It’s a simple select statement. And we are checking sy-subrc to check whether we obtained data or not. If no data is fetched then we raise appropriate exceptions by using RAISE command.

Source Code FM

Activate the FM.

Now activate the FM and test the FM by clicking executes. Pass a material number and see the output

Test FM

FM Output

Now lets create a Z program which uses the FM we created.

That’s it. It’s as simple as that. Every exception is given numbers by default and we can check sy-subrc for these numbers to identify the exception.