我想知道是否有人知道如何使用vba来保存在Excel中打开的.txt
文件?
我尝试用UserForm编写代码,但它给了我错误。
我想知道是否有可能让用户选择将其保存在他/她最喜欢的地方,还有他/她最喜欢的名字?
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
答案 0 :(得分:7)
错误是因为您的文件扩展名(xls)与您的文件类型(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
答案 1 :(得分:4)
我不确定为什么你在ActiveWorkbook.SaveAs之后使用Workbooks.Open。如果工作簿已经打开,这不是不必要的吗?
无论如何,要提示用户输入保存位置,请尝试根据需要修改以下内容:
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