我正在尝试在 Excel 中制作一个命令按钮,但在互联网上进行了大量搜索和尝试不同的代码后,我似乎找不到适合我个人需求的代码。 我希望在按下按钮后发生这种情况:
- 导出打开的 Excel 文件并将其保存到另一个文件位置,即c:/测试。
- 文档的名称应与 Excel 文件的名称相同。
到目前为止,我在互联网上搜寻后发现的最好的代码是这个。问题是最终用户必须实际按下“保存”才能保存文件。
Dim folderPath As String
Dim csvFile As String
folderPath = "C:\Users\username\Documents"
csvFile = Application.GetSaveAsFilename(InitialFileName:=folderPath, _
FileFilter:="CSV Files (*.csv), *.csv", Title:="Save As CSV")
If csvFile <> "" And csvFile <> "False" Then
Application.ScreenUpdating = False
ActiveSheet.Copy
On Error Resume Next
ActiveWorkbook.SaveAs fileName:=csvFile, FileFormat:=xlCSV, _
Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False, ConflictResolution:=xlUserResolution
On Error GoTo 0
'Close .csv workbook, leaving original workbook open
ActiveWorkbook.Close SaveChanges:=False
Application.ScreenUpdating = True
End If
End Sub
最佳答案
请尝试下一个简化的代码。除了运行代码之外,用户无需按任何操作。无论如何,它只会保存事件工作表:
Sub SaveCSV()
Dim folderPath As String, csvFile As String
folderPath = "C:\test"
'if test folder does not exist, it will be created:
If Dir(folderPath, vbDirectory) = "" Then MkDir folderPath
'The csv file name is obtained by replacing the active workbook extension:
csvFile = folderPath & "\" & Split(ActiveWorkbook.Name, ".")(0) & ".csv"
ActiveWorkbook.SaveAs filename:=csvFile, FileFormat:=xlCSV
ActiveWorkbook.Close SaveChanges:=False
End Sub
关于Excel - 导出为 csv 并保存到另一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65970154/