ASP 订阅所有【ASP】的日志

Use VBA SaveAs in Excel 2007-2016

Use VBA SaveAs in Excel 2007-2016

Information

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 (xls) in 97-2003 because there are no other Excel file formats before Excel 2007. 

But because there are so many new file formats in Excel 2007-2016, we shouldn't use code like this that does not specify the FileFormat parameter. In Excel 2007-2016, SaveAs requires you to provide both the FileFormat parameter and the correct file extension.

For example, in Excel 2007-2016, this will fail if the ActiveWorkbook is not an xlsm file
ActiveWorkbook.SaveAs "C:\ron.xlsm"

This code will always work
ActiveWorkbook.SaveAs "C:\ron.xlsm", fileformat:=52 
' 52 = xlOpenXMLWorkbookMacroEnabled = xlsm (with macro's in 2007-2016)


These are the main file formats in Excel 2007-2016, Note: In Excel for the Mac the values are +1

51 = xlOpenXMLWorkbook (without macro's in 2007-2013, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2013, xlsm)
50 = xlExcel12 (Excel Binary Workbook in 2007-2013 with or without macro's, xlsb)
56 = xlExcel8 (97-2003 format in Excel 2007-2013, 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).

Examples

Below are two basic code examples to copy the ActiveSheet to a new Workbook and save it in a format that matches the file extension of the parent workbook. The second example use GetSaveAsFilename to ask you for a file path/name. Example 1 you can use in Excel 97-2016 , Example 2 you can use in Excel 2000-2016.

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

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

                 Select Case Sourcewb.FileFormat
                Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
                Case 52:
                    If .HasVBProject Then
                        FileExtStr = ".xlsm": FileFormatNum = 52
                    Else
                        FileExtStr = ".xlsx": FileFormatNum = 51
                    End If
                Case 56: FileExtStr = ".xls": FileFormatNum = 56
                Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
                End Select

With one of the one liners from this list

FileExtStr = ".xlsb": FileFormatNum = 50 
FileExtStr = ".xlsx": FileFormatNum = 51
FileExtStr = ".xlsm": FileFormatNum = 52


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

FileExtStr = ".csv": FileFormatNum = 6
FileExtStr = ".txt": FileFormatNum = -4158
FileExtStr = ".prn": FileFormatNum = 36

 

Examples

Sub Copy_ActiveSheet_1()
'Working in Excel 97-2016
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    Set Sourcewb = ActiveWorkbook

    'Copy the sheet to a new workbook
    ActiveSheet.Copy
    Set Destwb = ActiveWorkbook

    'Determine the Excel version and file extension/format
    With Destwb
        If Val(Application.Version) < 12 Then
            'You use Excel 97-2003
            FileExtStr = ".xls": FileFormatNum = -4143
        Else
            'You use Excel 2007-2016
                Select Case Sourcewb.FileFormat
                Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
                Case 52:
                    If .HasVBProject Then
                        FileExtStr = ".xlsm": FileFormatNum = 52
                    Else
                        FileExtStr = ".xlsx": FileFormatNum = 51
                    End If
                Case 56: FileExtStr = ".xls": FileFormatNum = 56
                Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
                End Select
            End If
    End With

    '    'Change all cells in the worksheet to values if you want     '    With Destwb.Sheets(1).UsedRange     '        .Cells.Copy     '        .Cells.PasteSpecial xlPasteValues     '        .Cells(1).Select     '    End With     '    Application.CutCopyMode = False

    'Save the new workbook and close it
    TempFilePath = Application.DefaultFilePath & "\"
    TempFileName = "Part of " & Sourcewb.Name & " " & Format(Now, "yyyy-mm-dd hh-mm-ss")

    With Destwb
        .SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
        .Close SaveChanges:=False
    End With

    MsgBox "You can find the new file in " & TempFilePath

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub



Sub Copy_ActiveSheet_2()
'Working in Excel 2000-2016
    Dim fname As Variant
    Dim NewWb As Workbook
    Dim FileFormatValue As Long

    'Check the Excel version
    If Val(Application.Version) < 9 Then Exit Sub
    If Val(Application.Version) < 12 Then

        'Only choice in the "Save as type" dropdown is Excel files(xls)         'because the Excel version is 2000-2003
        fname = Application.GetSaveAsFilename(InitialFileName:="", _
        filefilter:="Excel Files (*.xls), *.xls", _
        Title:="This example copies the ActiveSheet to a new workbook")

        If fname <> False Then
            'Copy the ActiveSheet to new workbook
            ActiveSheet.Copy
            Set NewWb = ActiveWorkbook

            'We use the 2000-2003 format xlWorkbookNormal here to save as xls
            NewWb.SaveAs fname, FileFormat:=-4143, CreateBackup:=False
            NewWb.Close False
            Set NewWb = Nothing

        End If
    Else
        'Give the user the choice to save in 2000-2003 format or in one of the         'new formats. Use the "Save as type" dropdown to make a choice,Default =         'Excel Macro Enabled Workbook. You can add or remove formats to/from the list
        
        fname = Application.GetSaveAsFilename(InitialFileName:="", filefilter:= _
            " Excel Macro Free Workbook (*.xlsx), *.xlsx," & _
            " Excel Macro Enabled Workbook (*.xlsm), *.xlsm," & _
            " Excel 2000-2003 Workbook (*.xls), *.xls," & _
            " Excel Binary Workbook (*.xlsb), *.xlsb", _
            FilterIndex:=2, Title:="This example copies the ActiveSheet to a new workbook")
         'Find the correct FileFormat that match the choice in the "Save as type" list
        If fname <> False Then
            Select Case LCase(Right(fname, Len(fname) - InStrRev(fname, ".", , 1)))
            Case "xls": FileFormatValue = 56
            Case "xlsx": FileFormatValue = 51
            Case "xlsm": FileFormatValue = 52
            Case "xlsb": FileFormatValue = 50
            Case Else: FileFormatValue = 0
            End Select

            'Now we can create/Save the file with the xlFileFormat parameter             'value that match the file extension
            If FileFormatValue = 0 Then
                MsgBox "Sorry, unknown file extension"
            Else
                'Copies the ActiveSheet to new workbook
                ActiveSheet.Copy
                Set NewWb = ActiveWorkbook

                'Save the file in the format you choose in the "Save as type" dropdown
                NewWb.SaveAs fname, FileFormat:= _
                             FileFormatValue, CreateBackup:=False
                NewWb.Close False
                Set NewWb = Nothing

            End If
        End If
    End If
End Sub

 



上一篇: VB编写的数据库程序在Win7 SP1编译无法在XP系统上使用的问题
下一篇: 这是最新的一篇日志
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 17 | 引用: 0 | 查看次数: 1159
Wilfredo[2017-11-17 03:23 PM | | Mail To:wilfredoruzicka@gmail.com | 173.44.165.81 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Alma[2017-11-09 09:09 PM | | Mail To:alma.spradling@gmail.com | 42.201.137.229 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Clemmie[2017-11-02 06:36 PM | | Mail To:clemmie.landseer@gmail.com | 191.101.23.209 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Randi[2017-10-31 02:18 AM | | Mail To:randioferrall@web.de | 191.101.23.209 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Stuart[2017-10-29 04:26 AM | | Mail To:stuart.ratcliffe@zoho.com | 23.19.101.105 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Thaddeus[2017-10-24 04:52 AM | | Mail To:thaddeusfawsitt@mailworks.org | 196.247.18.156 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Roseanne[2017-10-23 11:44 AM | | Mail To:roseanneblacklock@gmail.com | 82.211.9.227 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Mona[2017-10-22 02:45 AM | | Mail To:mona_andrus@gmail.com | 198.23.216.145 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Alana[2017-06-01 09:33 AM | | Mail To:alanalauer@googlemail.com | 196.16.1.193 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
Francine[2017-05-22 04:49 AM | | Mail To:francinepinedo@gmail.com | 107.173.46.203 | del | 通过审核 | 回复回复]
[此评论正在审核中,只有博主及评论作者可见]
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 关闭 | [img]标签 关闭