# Calculate Opening and Closing Stock

Hi all,

Plz tell me logic how to calculate Opening Stock and Closing Stock of material of any particular date of month...........

##### Sneha Pacharnereplied

heres the code to calculate stock of previous period(closing stock)

DATA : it_mard LIKE mard OCCURS 0 WITH HEADER LINE.

DATA : BEGIN OF t_mard OCCURS 0 ,

matnr LIKE mseg-matnr,

labst LIKE mard-labst,

END OF t_mard.

DATA : it_mardh TYPE mardh.

DATA : buper LIKE t009b-poper,

gjahr LIKE t009b-bdatj.

DATA : p_buper LIKE t009b-poper,

p_gjahr LIKE t009b-bdatj.

DATA : dt LIKE sy-datum.

*CLOSING STOCK OF PREVIOUS PERIOD

dt = sy-datum.

*get current period

CALL FUNCTION 'DATE_TO_PERIOD_CONVERT'

EXPORTING

i_date = dt

i_periv = 'M3' "apr to march 4 spl periods

IMPORTING

e_buper = buper

e_gjahr = gjahr

EXCEPTIONS

input_false = 1

t009_notfound = 2

t009b_notfound = 3

OTHERS = 4.

*fetch previous period

CALL FUNCTION 'CKML_F_GET_PREVIOUS_PERIOD'

EXPORTING

input_period = buper

input_year = gjahr

input_periv = 'M3'

IMPORTING

previous_period = p_buper

previous_year = p_gjahr.

SELECT SINGLE * FROM mardh

WHERE matnr = p_matnr

AND werks = p_werks

AND lfmon = p_buper

AND lfgja = p_gjahr.

IF sy-subrc = 0.

<b>CLOSING STOCK</b> = mardh-labst.

ENDIF.

*to calculate current stock-----

SELECT * FROM mard

INTO CORRESPONDING FIELDS OF TABLE it_mard

WHERE matnr = it_marc-matnr

AND werks = p_werks.

IF NOT it_mard[] IS INITIAL.

LOOP AT it_mard.

t_mard-matnr = it_mard-matnr.

t_mard-labst = it_mard-labst.

COLLECT t_mard.

ENDLOOP.