Run time error 1004 for saving excel file (VBA required)

后端 未结 2 1171
北荒
北荒 2021-01-06 12:39

I was wondering if anyone knows how to use vba to save a .txt file that is opened in excel?

I have tried writing a coding with a UserForm, but it is giv

2条回答
  •  有刺的猬
    2021-01-06 12:55

    The error is because your file extension (xls) doesn't match your file type (OpenXMLWorkbookMacroEnabled). You would need the xlsm extension.

    Sub Command1Click()
    
        Dim lResp As Long
        Dim sCurrFile As String
        Dim sNewFile As String
    
        Const sPROMPT As String = "Do you want to save?"
        Const sFILTER As String = "*.xlsm, *.xlsm"
    
        lResp = MsgBox(sPROMPT, vbYesNo, "Save File")
    
        If lResp = vbYes Then
            sCurrFile = ActiveWorkbook.FullName 'save current file name
            sNewFile = Application.GetSaveAsFilename(, sFILTER) 'get new file name
            If sNewFile <> "False" Then 'user didn't cancel
                ActiveWorkbook.SaveAs sNewFile, xlOpenXMLWorkbookMacroEnabled
                ActiveWorkbook.Close False 'close new file
                Workbooks.Open sCurrFile 'open previous text file
            End If
        Else
            Unload Me
        End If
    
    End Sub
    

提交回复
热议问题