运行时错误1004用于保存excel文件(需要VBA)

我想知道是否有人知道如何使用VBA来保存在Excel中打开的.txt文件?

我已经尝试用UserForm编写代码,但它给我错误。

我想知道是否有可能让用户select将它保存在他/她最喜欢的地方,还有他/她最喜欢的名字?

  Public Sub CommandButton1_Click() Dim YesOrNoAnswerToMessageBox As String Dim QuestionToMessageBox As String Dim CurrentFile As String QuestionToMessageBox = "Do you want to save?" YesOrNoAnswerToMessageBox = MsgBox(QuestionToMessageBox, vbYesNo, "Save file") If YesOrNoAnswerToMessageBox = vbNo Then Unload Me 'Cancellation command Else CurrentFile = ThisWorkbook.FullName ActiveWorkbook.SaveAs "C:\myfile.xls", FileFormat:=52 Workbooks.Open CurrentFile End If End Sub 

错误是因为您的文件扩展名(xls)与您的文件types(OpenXMLWorkbookMacroEnabled)不匹配。 您将需要xlsm扩展名。

 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 

我不确定你为什么使用Workbooks.Open后ActiveWorkbook.SaveAs。 如果工作簿已经打开,这不是没有必要吗?

无论如何,要提示用户保存位置,请根据需要修改以下内容:

 Sub DoooooooooooooooooooIt() Dim fd As FileDialog Set fd = Application.FileDialog(msoFileDialogSaveAs) With fd .Show If .SelectedItems.Count > 0 Then Debug.Print .SelectedItems(1) End If End With End Sub