You need be more careful in what variables you are referencing.
Take this little block of code:
271 ** Create new variable that contains numeric values of s_cmstdtc;
272 ** If the first character of s_cmstdtc is 'U', leave numeric value missing;
273
274 format sort date9.;
275 sort = input(s_cmstdtc, ??date9.);
276 if upcase(substrn(sort,1,1))= "U" then sort = .;
You convert the characters in S_CMSTDTC into a date value in SORT. But then try to use a character function on the numeric variable SORT. Didn't you mean to check S_CMSTDTC? Also shouldn't you check it BEFORE trying to convert it to a date?
But even easier just delete the last line since the assignment statement above it will have already converted strings that are not valid dates (including strings that start with the letter U) to missing values.
Also look at this block of code earlier
263 ** Create new variable for s_cmtrt;
264 if (s_cmtrt ne ' ') then medname = Medication;
265 else if (s_cmtrt eq ' ') then Medication = 'None';
The comment mentions only one input variable, but the IF statement is reading from some other variable named MEDICATION. Then the ELSE statement will modify that MEDICATION variable, but do nothing with the MEDNAME variable. Did you mean to change the MEDICATION variable? Did you mean to not set the MEDNAME variable to anything? Is it a new variable or an existing variable that is being read in from the source dataset?