Excel With SAS
Excel With SAS
Excel With SAS
Applications Development
Paper 022-31
Introduction
This paper and the presentation are an introduction to a SAS-with-Excel self-study collection of sixty macros and twenty-six sample programs (with substantial comments), and supporting files, which are available at no charge from the author via email (at bessler@execpc.com). To find out more about the Excel commands used here to work with DDE, or to find other commands or command options not used here, you must consult the documentation in Macrofun.hlp. To get that information, you must install Macrofun.hlp by initially downloading Macrofun.exe from the Microsoft Download Center, and then run the .exe file. If you are not experienced using the Download Center, you can find the right part of it by using google.com to search for macrofun.exe, or instead you could try this URL: http://support.microsoft.com:80/support/kb/articles/Q128/1/85.ASP.
SUGI 31
Applications Development
Some of the Cell Formatting Options Font controls available include: font, style, size, color, and underline. Cell background can be filled with color. Cell sizing is possible, and column or row AutoFit and column or row Hide/Unhide. Cell alignment, cell merge, text wrap, etc. can be done. Borders can be created, e.g., to section the worksheet. Cell content can be indented, using two tricks shown in sample programs.
Some of the Worksheet Controls Select worksheet, cells, rows, columns Freeze/Unfreeze panes Turn AutoFilter On/Off Generate subtotals in a worksheet Control/Change levels for Excel subtotals (or create multiple custom sheets for various levels of totals) Activate a specific worksheet in a workbook Create additional worksheets in a workbook Delete unused worksheets in a workbook
Some of the Other Manipulation Possibilities Insert/Delete columns or rows Find, Find and Replace cell contents Copy cells, Move cells Use formulas to create new column(s) Use Zoom to shrink or enlarge a worksheet Control the Message text box in the lower left corner of the Excel window
SUGI 31
Applications Development
sssss is end/bottom row number ttt is end/right column number Row/column numbers with leading zeros are permissible. Other ways to make selections of cells are as follows: RpppppCqqq Rppppp:Rsssss Rppppp Cqqq:Cttt Cqqq single cell range of rows single row range of columns single column
See the section Insert a Heading for the New Column 4 for a simple example of the FILENAME statement used for writing data with DDE. For more examples of writing data to Excel from SAS, see Reference 1. Coding the Cell Selection You are not required to permanently hard code it. You can use DDE select functions to operate based on criteria assigned by you (as in some examples below). Or you can use macro program code to determine the selection target dynamically (as in examples from the tools package available via email). Excel DDE Commands Microsoft developed DDE commands for an earlier version of Excel than the current one. I have used them with various versions of Excel and Windows. Almost all of the commands (that I have tried) work for me, but I can offer no guarantees. The commands are documented in Macrofun.hlp, which you can download from Microsoft as mentioned above. Macrofun is an abbreviation for Macro Functions, not Macro Fun, but these macros functions are fun to use. They do not require use of Excel macros. Please be aware that not every DDE command works (e.g., rename worksheets, create subtotals, . . .), and some command options may not work. Nevertheless, what does work is an enormous tool set! true / false Values for DDE Commands These are used to turn options On / Off in DDE command parameter assignments. For some commands you are required to use 1 / 0 instead. Basic DDE Functions 1. 2. 3. 4. Start Excel: provides a default empty workbook, with three worksheets Open an existing workbook Save As of the current workbook with a new name Exit Excel
All of the examples presented in the Tour of DDE Examples assume that Steps 1 and 2 of Basic DDE Functions have already been completed.
SUGI 31
Applications Development
Starting Excel from SAS For other versions of Microsoft Office or Excel than what I used for my development, you may need to use a folder sequence in your code different from that used in this Excel start-up code: x '"C:\Program Files\Microsoft Office\Office\EXCEL.exe"'; data _null_; z=sleep(3); /* wait 3 seconds for Excel to start */ run; The above program opens a new workbook, with three empty worksheets: Sheet1, Sheet2, and Sheet3. Open Existing Workbook from SAS data _null_; /* talk to DDE, no output data */ file DDEcmds; put '[open("c:\YourFolder\YourWorkbook.xls")]'; x=sleep(3); /* wait 3 seconds for it to open */ run; Finished Workbook Save As data _null_; file DDEcmds; put '[error(false)]'; put '[save.as ("c:\OtherFolder\DifferentFileName.xls")]'; x=sleep(1); run; Exiting Excel from SAS data _null_; file DDEcmds; put '[error(false)]'; put '[quit()]'; /* empty parenthesis */ run; The error(false) command tells Excel that you do not want a prompt to ask for confirmation of intention. SAS-with-Excel Libraries of Programs and Macros (available via email) 26 heavily commented sample programs 5 empty, but specially preformatted, spreadsheets to use in sample programs Text files of color definition information 60 macros for your use, with example invocations in sample programs
Running sample programs with OPTIONS MPRINT; shows generated SAS code in the SAS log. This enables you to understand what any macro does. If you wish to avoid use of a macro, you can copy generated code from the SAS log, strip off the MPRINT prefix at the left margin, and adapt that code to other uses without the macro.
SUGI 31
Applications Development
All illustrations in this paper present screen images at full page width to maximize readability. There will be pages with lots of white space at the bottom. By limiting each page to one screen image at most, it is easier to present code and its result together on the same page.
SUGI 31
Applications Development
Font Formatting Step 1 Activate worksheet (if not already there). Select the cells to be formatted data _null_; file DDEcmds; put '[workbook.activate("CLASS")]'; put [select("R5C3:R7C5")]'; run; Cells to be formatted Selected:
SUGI 31
Applications Development
Font Formatting Step 2 Lets use: font Verdana style Bold size 16 point (Excel) color 3 - red Heres how (those commas are very important, and represent unused but available options): data _null_; file DDEcmds; put '[font.properties("Verdana","Bold",16,,,,,,,3)]'; run; The font is changed, but is obscured by the cell selection box and shading:
SUGI 31
Applications Development
Font Formatting Step 3 After the block of cells has been formatted, the necessary predecessor select("R5C3:R7C5")command leaves them highlighted (just as a mouse would). But I want to see the new font color. So, move the focus with: data _null_; file DDEcmds; put '[select("R1C1")]'; run; I can see clearly now.
Font Formatting Can Be Done All In One Step data _null_; File DDEcmds; put '[workbook.activate("Class")]'; put '[select("R5C3:R7C5")]'; put '[font.properties("Verdana","Bold Italic",16,,,,,,,3)]'; put '[select("R1C1")]'; run;
SUGI 31
Applications Development
DDE Command Format In a command of the form put '[CommandName(arg1,arg2,...,argN)]'; the CommandName may be multi-word, dot-separated. For an example with several (in this case, four) command arguments, there are three ways to indicate omission of one argument if at start of list: ,arg2,arg3,arg4 if in middle of list: arg1,,arg3,arg4 if at end of list: arg1,arg2,arg3 (i.e., just omit)
Color the Cell Background data _null_; file DDEcmds; put '[select.special(11)]'; /* select the last cell of worksheet */ put '[patterns(1,,3,true)]'; /* color it red */ put '[select("R1C1")]'; /* move the highlight to the first cell to see the color with no halo */ run;
SUGI 31
Applications Development
Remove the Background Color (or reverse whatever was the last command) data _null_; file DDEcmds; put '[undo()]'; run; Color Undone (but focus returns to the cell for which the prior action is undone):
10
SUGI 31
Applications Development
Using Formulas in Excel Normally, one could create all the Excel report data in SAS pre-spreadsheet-load processing. Suppose, however, we want columns derived from Excel subtotals. For demo only, we will work with simple spreadsheet content, without subtotals. With subtotals present, the use of Excel formulas works the same. Insert a New Column to the Left of Column 4 data _null_; file DDEcmds; put '[select("C4")]'; put '[insert(4)]'; /* 4 specifies type of INSERT */ run;
11
SUGI 31
Applications Development
Excel Format the (Still Empty) Cells in Column 4 Like SAS Format 4.1 /* no need to re-select the column, because focus is still there */ data _null_; file DDEcmds; put '[Format.Number("#0.0")]'; run; Insert a Heading for the New Column 4 filename CELL1 DDE "EXCEL|Class!R1C4"; data _null_; file CELL1; put 'Lbs./Yr.'; run;
12
SUGI 31
Applications Development
Prepare for a Division Operation Column 3 is to be the divisor. For this demo, set some of its cells to null (missing) values, and some other cells to zero values. data _null_; file DDEcmds; put '[select("C3")]'; put '[formula.replace("16","",1,,false,false)]'; put '[formula.replace("12","0",1,,false,false)]'; put '[select("R1C3")]'; /* remove highlight */ run; Note the Presence Now of Some Zero Values and a Null in the Age Column:
13
SUGI 31
Applications Development
Divide Weight By Age data _null_; file DDEcmds; put '[select("R2C4")]'; put '[formula.fill("=RC[+2]/RC[-1]","R2C4:R20C4")]'; run; Some (Expected) Error Messages Appear:
14
SUGI 31
Applications Development
Get Rid of the Error Message #DIV/0! data _null_; file DDEcmds; put '[select.special(3,16)]'; put '[clear]'; run; Cleared Cells Remain Selected:
15
SUGI 31
Applications Development
Replace Nulls with N/A data _null_; file DDEcmds; put '[formula.replace("","N/A",1,,false,false)]'; put '[select("R1C4")]'; /* remove the highlight */ run; Almost Finished:
16
SUGI 31
Applications Development
Make the Headings Bold, and AutoFit the Columns data _null_; file DDEcmds; put '[select("R1")]'; put '[font.properties("","Bold")]'; /* "", = font name unchanged put '[select("C1:C6")]'; put '[column.width(,,,3)]'; /* commas required /* 3 = AutoFit put '[select("R1C1")]'; /* remove the selection highlight run; Better, But Still Not Finished:
*/ */ */ */
17
SUGI 31
Applications Development
Align Columns 2 and 3 data _null_; file DDEcmds; put '[select("C2:C3")]'; put '[alignment(3,false,3,0)]'; put '[select("C4")]'; put '[alignment(4, false,3,0)]'; put '[select("R1C1")]'; run;
/* /* /* /*
*/ */ */ */
18
SUGI 31
Applications Development
Excel Format the Height and Weight Data Like SAS Format 4.1 data _null_; file DDEcmds; put '[select("C5:C6")]'; put '[format.number("#0.0")]'; put '[select("R1C1")]'; /* remove the column selection highlight */ run; Finished:
19
SUGI 31
Applications Development
Conclusion
There are other ways to generate Excel reports with SAS, but DDE is the method I prefer. Its astonishing power has impressed me. The examples above are only a small subset of what you can do with DDE. Though still just a larger subset of DDEs power, available at no charge via email at the address below are my 60 macros, 26 sample programs (commented), and supporting files, to implement the above and other functions, including: Cell sizing Column or row Hide/Unhide Cell merge, text wrap, etc. Create borders to section the worksheet Indent cell content Freeze/Unfreeze panes Turn AutoFilter On/Off Generate subtotals in a worksheet Control/Change levels for Excel subtotals (or create custom worksheets for various levels of totals) Create additional worksheets in a workbook, Delete unused worksheets in a workbook Delete columns or rows Copy cells, Move cells Use Zoom to shrink or enlarge a worksheet Control the Message text box in the lower left corner of the Excel window Run Excel macros
Author Information
Your requests, questions, comments, suggestions, and other DDE solutions are welcome. LeRoy Bessler PhD, Fox Point, PO Box 96, Milwaukee, WI 53201, USA, bessler@execpc.com
20