loopserror-handlingsasmacrosdo-loops

SAS: How do I skip an error in a do loop?


I am trying to skip a selection in the do loop if there is an error.

I am running the following code:

  %macro date_loop(start,end);
   %let start=%sysfunc(inputn(&start,anydtdte9.));
   %let end=%sysfunc(inputn(&end,anydtdte9.));
   %let dif=%sysfunc(intck(weekday,&start,&end));
     %do i=0 %to &dif;
      %let date=%sysfunc(intnx(weekday,&start,&i,b),yymmddn8.);
      %put &date;
       MY CODE TO OPEN FILE WITH THAT DATE
     %end;
   %mend date_loop;

   %date_loop(01jan2015,02jan2015)

There isn't a file with the January 1, 2015 date, as I expect. I get the following error.

ERROR: File 20150101.DATA does not exist

Rather than take out holidays, I would prefer to have SAS skip that date and go to the next one. Oddly, it seems to capture the January 2, 2015 file. Then the January 2, 2015 part of the loop runs, and I get the January 2, 2015 file again. Is there a way for it to skip the date if the file doesn't exist?


Solution

  • To check if a SAS dataset exists then use the EXIST() function. To test if a disk file exists use the FILEEXIST() function.

    ...
     %do i=0 %to &dif;
      %let date=%sysfunc(intnx(weekday,&start,&i,b),yymmddn8.);
      %let dataset = MYLIB.MYFILE&date ;
      %if %sysfunc(exist(&dataset)) %then %do;
         MY CODE THAT uses &dataset 
      %end;
     %end;