在维护文件结构时强制另存为XLSM

时间:2012-08-24 14:36:09

标签: excel-vba filenames before-save vba excel

所以我正在使用XLTM文件,我希望用户确保它们保存为XLSM。当他们点击“保存”时,这工作正常,但我发现当他们点击“另存为”时,文件将保存为“* .xlsm.xlsm”。我有点迷失了如何确保用户保存为XLSM,同时保持文件名为“filename.xlsm”而不是“filename.xlsm.xlsm”。

    'Action makes sure the user saves as XLSM file type.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) 
    Dim FileNameVal As String 
    If SaveAsUI Then 
        FileNameVal = Application.GetSaveAsFilename(, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm") 
        Cancel = True 
        If FileNameVal = "False" Then 'User pressed cancel
            Exit Sub 
        End If 

        Application.EnableEvents = False 
        ThisWorkbook.SaveAs Filename:=FileNameVal & ".xlsm", FileFormat:=ThisWorkbook.FileFormat 
        Application.EnableEvents = True 
    End If 
End Sub 

我认为问题可能是写在“.xlsm”中:

ThisWorkbook.SaveAs Filename:=FileNameVal & ".xlsm", FileFormat:=ThisWorkbook.FileFormat 

但是,如果没有写“.xlsm”,我会发现该文件会另存为坏文件后缀。 (例如,如果我的XLTM文件名为Template(File001).xltm,并且用户打开一个新的模板文件,它将另存为模板(File001)1(认为“1)1”是文件类型。)

它可能是我的代码的结构,所以我需要指导如何修改它。

1 个答案:

答案 0 :(得分:5)

问题似乎已经存在,因为模板会在实际最初保存之前将文件命名为“Template(1)1”。这改变了Excel保存文件的方式,因此在初始保存和进一步保存(已包含文件扩展名)之间进行对比的最简单方法是使用if-then语句判断扩展是否已存在。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim FileNameVal As String
If SaveAsUI Then
    FileNameVal = Application.GetSaveAsFilename(, "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
    Cancel = True
    If FileNameVal = CStr(False) Then 'User pressed cancel
        Exit Sub
    End If
    Application.EnableEvents = False
        If Right(ThisWorkbook.Name, 5) <> ".xlsm" Then
            ThisWorkbook.SaveAs Filename:=FileNameVal & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
        Else
            ThisWorkbook.SaveAs Filename:=FileNameVal, FileFormat:=xlOpenXMLWorkbookMacroEnabled
        End If
    Application.EnableEvents = True
End If
End Sub