Home » excel » Exporting multiple sas datasets into multiple excel sheets with macro?

Exporting multiple sas datasets into multiple excel sheets with macro?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am looking if there is a macro that would export multiple datasets into separate excel worksheets within a workbook. Would be great if I could have 10 sheets per workbook.

I can do it the usual way as below, but I have more than 100 datasets to export:

PROC EXPORT DATA=HAVE;
OUTFILE= "S:\MYEXCEL.xlsx" 
        DBMS=EXCEL REPLACE;
SHEET="NEW_SHEET"; 
RUN;

Thank you!

How to&Answers:

The general concept is that you would do something like this:

%macro export_data(file=,data=,sheet=);
proc export data=&data.
outfile="&file."
dbms=excel replace;
sheet="&sheet.";
run;
%mend export_data;

Then you need to construct your export macro calls however you want. Get a dataset with one row per dataset (use dictionary.tables in SQL or sashelp.vtable in data step) and work out however you want to the logic of the sheet names and how many workbooks you need. Google data-driven macro calls for more information.

Answer:

Provided you have ‘SAS/Access to PC FIle formats’ licensed, this little macro does it effortlessly:

%macro SASToExcel(ImportLibrary=, ExportLocation=);

    ods output members = _Members;
    proc datasets lib = &ImportLibrary; run; quit;

    proc sql;
        select count(Name) into :NumOfDatasets from _Members;
        select Name into :Dataset1-:Dataset%trim(%left(&NumOfDatasets)) from _Members;
    quit;

    %do index = 1 %to &NumOfDatasets;
        proc export data=&ImportLibrary..&&Dataset&index.
        outfile="&ExportLocation"
        dbms=excel replace;
        sheet="&&Dataset&index";
        run;
    %end;

    proc datasets;
        delete _Members;
    quit;

%mend;

%SASToExcel(ImportLibrary=raw, ExportLocation = c:\test.xlsx);