我正在使用Excel 2010,并且拥有一个支持各种处理选项的用户表单(即按预定义范围排序,获取统计数据和可怕的'导出'(SaveAs)。我想允许用户导出其中一个工作表为CSV或XLSX。
问题是当我使用SaveAs保存为CSV时,它会将工作表重命名为我选择的文件名(减去扩展名)。我搜索了几个小时,但没找到任何提供解决方案的地方。我找到了一个5年以上的Stack帖子,但它没有解决方案(见How to stop renaming of excelsheets after running the save macro)
任何帮助将不胜感激!谢谢!
以下是代码:
Dim ws As Excel.Worksheet
Dim strSaveName As String
Dim strThisName As String
strThisName = ThisWorkbook.Path & ThisWorkbook.Name
strSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.csv), *.csv")
Set ws = Worksheets("Export")
ws.SaveAs Filename:=strSaveName, FileFormat:=xlCSV
'I do the following TO UNDO THE RENAME <GROAN> (for now just saving as 0.csv)
Sheets("0").Name = "Export"
' Then the following is to regain my original filename since I will continue working...
ws.SaveAs Filename:=strThisName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
答案 0 :(得分:3)
预先使用ws.Copy而不使用args然后保存新工作簿
e.g。使您的代码适合:
Dim ws As Excel.Worksheet
Dim strSaveName As String
strSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.csv), *.csv")
Set ws = Worksheets("Export")
'Copy the ws to a new workbook
ws.Copy
'With the new wb:
With Workbooks(Workbooks.Count)
'Save and close the new workbook
.SaveAs Filename:=strSaveName, FileFormat:=xlCSV
.Close False
End With
P.S。我假设您有代码来处理单击GetSaveAsFilename上的取消,并且为了清楚起见而将其删除;)