Skip to content

Instantly share code, notes, and snippets.

@statgeek
Created February 16, 2022 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save statgeek/49e54641ceaf58bc4fe5dc2062bc89cb to your computer and use it in GitHub Desktop.
Save statgeek/49e54641ceaf58bc4fe5dc2062bc89cb to your computer and use it in GitHub Desktop.
SAS - export to SAS and split file by number of records or size of data set
*This macro will export a file to a data set and split it based on the number of records per sheet;
%macro export_split (dsn=, size=);
%*Get number of records and calculate the number of files needed;
data _null_;
set &dsn. nobs=_nobs;
call symputx('nrecs', _nobs);
n_files=ceil(_nobs/ &size.);
call symputx('nfiles', n_files);
stop;
run;
%*Set the start and end of data set to get first data set;
%let first=1;
%let last=&size.;
%*Loop to split files;
%do i=1 %to &nfiles;
%*Split file by number of records;
proc export data= &dsn. (firstobs=&first obs=&last) outfile='/home/fkhurshed/Demo1.xlsx' dbms=xlsx; Sheet="Page&i.";
run;
%*Increment counters to have correct first/last;
%let first = %eval(&last+1);
%let last = %eval((&i. + 1)*&size.);
%end;
%mend export;
*Example call;
*After running this, you should find 9 data sets named Split1-Split9;
%export_split(dsn=sashelp.cars, size=50);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment