The code that you execute outside of your macro also works fine inside the macro. However, the problem is that you overwrite it again with the original value of your input S in the second if/else-block.
%else %if &idx1_dw=%eval(&idx2_dw + 1) %then %do;
%let cfun=%qsysfunc(tranwrd(&S,%str(UNUN),%str(UN)));
%let cfun=%qsysfunc(tranwrd(&S, %str(UN/UN), %str(UN)));
%end;
The second let-statement uses the original input S. Since the string "UN/UN" does not appear, nothing is translated and CFUN is set equal to S. This is what you get as an output at the end.
You probably want to modify the second let-statement to have CFUN as an input. The full code then looks like this:
%macro DROPUN(S);
%let idx2_dw=%sysfunc(index(&s,JUN));
%let idx1_dw=%sysfunc(index(&s,UN));
%if &idx2_dw=0 %then %do;
%let cfun=%sysfunc(tranwrd(&S,UN,'07'x));
%let cfun=%sysfunc(compress(&cfun,'07'x));
%end;
%else %if &idx1_dw=%eval(&idx2_dw + 1) %then %do;
%let cfun=%qsysfunc(tranwrd(&S,%str(UNUN),%str(UN)));
%let cfun=%qsysfunc(tranwrd(&cfun, %str(UN/UN), %str(UN)));
%end;
%else %if &idx1_dw=1 %then %do;
%let l_dw=%eval(%length(&S)-2);
%let cfun=%substr(&S,3,&l_dw);
%end;
%put after dw is &cfun;
%mend DROPUN;
%dropun(2021JUNUN);
This gives the correct output.
after dw is 2021JUN
... View more