excel 正在尝试使用VBA代码创建新工作簿(.xlsm格式)

afdcj2ne  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(222)

我试图使用现有工作簿的模板创建多个工作簿。现有工作簿保存为. xlsm。当我试图创建新工作簿时,它给我一个错误。但在运行代码后,我有一个弹出消息,询问我是否要“继续保存为无宏工作簿”
如果单击“否”,则会出现错误消息:错误:运行时错误“1004.”VB项目与XLM工作表不能保存在未启用宏得工作簿中.
如果单击“是”,则会出现错误消息:错误:此扩展名不能用于所选文件类型。我知道这是因为我为新工作簿指定了.xlsm扩展名,如果希望将其保存为无宏工作簿,则需要将其更改为.xlsx。

Sub vba_create_workbook()
    
    Workbooks.Add Template:="Folder Path\File Name.xlsm"
    ActiveWorkbook.SaveAs "Folder Path\File Name.xlsm"
    
    Workbooks.Add Template:="Folder Path\File Name.xlsm"
    ActiveWorkbook.SaveAs "Folder Path\File Name.xlsm"
  
End Sub

是否有任何方法可以将新创建的文件直接保存为启用宏的工作簿,即(.xlsm)?

js81xvg6

js81xvg61#

从模板创建新工作簿

利用率

Sub RefNewTemplateTEST()
    
    Const SRC_FILE_PATH As String = "Folder Path\Source File Name.xlsm"
    Const DST_FILE_PATH As String = "Folder Path\Destination File Name.xlsm"
    
    Dim dwb As Workbook: Set dwb = RefNewTemplate(SRC_FILE_PATH, DST_FILE_PATH)
    
    If dwb Is Nothing Then Exit Sub
    
    ' Continue using dwb.
    
    MsgBox "Created '" & dwb.Name & "' from template.", vbInformation
    
End Sub

功能

Function RefNewTemplate( _
    TemplatePath As String, _
    DestinationPath As String) _
As Workbook
    Const PROC_TITLE As String = "Reference New Workbook From Template"
    
    If StrComp(TemplatePath, DestinationPath, vbTextCompare) = 0 Then
        MsgBox "The Template and Destination paths are the same.", _
            vbCritical, PROC_TITLE
        Exit Function
    End If
    
    Dim dwb As Workbook, ErrNum As Long
    Dim ErrDescription As String, MsgString As String
    
    On Error Resume Next
        Set dwb = Workbooks.Add(Template:=TemplatePath)
        ErrNum = Err.Number
        ErrDescription = Err.Description
    On Error GoTo 0
    
    If ErrNum <> 0 Then
        Select Case ErrDescription
            Case "Method 'Add' of object 'Workbooks' failed"
                MsgString = "The template is already open."
            Case "Sorry, Excel can't open two workbooks with " _
                    & "the same name at the same time."
                MsgString = "A file with the same name as the template is open."
            Case Else
        End Select
        MsgBox "Run-time error '" & ErrNum & "':" & vbLf & vbLf _
            & ErrDescription & IIf(Len(MsgString) > 0, vbLf & vbLf, "") _
            & MsgString, vbCritical, PROC_TITLE
        Exit Function
    End If
        
    Application.DisplayAlerts = False ' overwrite without confirmation
        On Error Resume Next
            dwb.SaveAs DestinationPath, xlOpenXMLWorkbookMacroEnabled
            ErrNum = Err.Number
            ErrDescription = Err.Description
        On Error GoTo 0
    Application.DisplayAlerts = True
     
    If ErrNum <> 0 Then
        dwb.Close SaveChanges:=False
        MsgBox "Run-time error '" & ErrNum & "':" & vbLf & vbLf _
            & ErrDescription, vbCritical
        Exit Function
    End If
  
    Set RefNewTemplate = dwb
  
End Function

相关问题