Back
Excel

Use the VBA SaveAs Method in Excel 2007

Today’s author is Ron de Bruin , an Excel MVP. You can find more useful tips and links to Excel add-ins at his website: http://www.rondebruin.nl/

You see a lot of old SaveAs code that does not specify the FileFormat
parameter. In Excel versions before Excel 2007, code without this parameter
will not cause too many problems because Excel will use the current FileFormat
of the existing file — and the default FileFormat for new files is a normal workbook. But because there are so many new file formats in Excel 2007, you shouldn’t
use code that doesn’t specify the FileFormat parameter.

In Excel 2007, the SaveAs method requires you to provide both the FileFormat parameter and the correct file extension.

For example, in Excel 2007 this line of code will fail if the ActiveWorkbook is not an .xlsm file:

But this code will always work:

These are the main file formats in Excel 2007:

51 = xlOpenXMLWorkbook (without macro’s in 2007, .xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro’s in 2007, .xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007 with or without macro’s, .xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007, .xls)

Note: I always use the FileFormat numbers instead of the defined constants
in my code so that it will compile OK when I copy the code into an Excel
97-2003 workbook. (For example, Excel 97-2003 won’t know what the
xlOpenXMLWorkbookMacroEnabled constant is.)

Example

At the end of this section is a basic VBA code example for a macro named Copy_ActiveSheet_New_Workbook() that copies the ActiveSheet to a new Workbook and then saves it in a format that matches the file extension of the parent workbook.
Note: You can use this macro in Excel 97-2007.

If you run the code in Excel 2007, it will look at the FileFormat of the parent workbook and save the new file in that format. However, if the parent workbook is an .xlsm file and there is no VBA code in the new workbook, the code will save the new file as an .xlsx file.
If the parent workbook is not an .xlsx, .xlsm or .xls file, then it will be saved as an .xlsb file.

If you always want to save in a certain format you can replace this part of the macro:

Or maybe you want to save the one sheet workbook to .csv, .txt, or .prn. (you can use this also if you run the macro in Excel 97-2003)

Here’s the full code example.