[英]file to saveas CSV format iin excel vba
i have used the following code for saving my active worksheet to CSV, but the output file is not found in that folder. 我使用以下代码将我的活动工作表保存为CSV,但在该文件夹中找不到输出文件。 What is the problem with the code? 代码有什么问题?
code for your reference: 代码供您参考:
Sub Save_CSV()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
SaveNAme = "INDENTED_BOM"
SavePath = Dir("C:\Users\350153\Desktop\AUTOMATION (STRUCTURES)")
Range("A1:D150").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Selection.Copy
Workbooks.Add
With ActiveSheet.Range("A2")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
ActiveSheet.Columns("A:D").AutoFit
ActiveWorkbook.SaveAs Filename:=SavePath & SaveNAme & ".csv" _
, FileFormat:=xlCSVWindows, CreateBackup:=False
ActiveWorkbook.Save
ActiveWindow.Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Task Finished", vbInformation, "Finished"
End Sub
You can do this without copy/paste, because the Worksheet
object has a SaveAs
method, so there is no need to do: 您可以在不复制/粘贴的情况下执行此操作,因为Worksheet
对象具有SaveAs
方法,因此无需执行以下操作:
Workbooks.Add
通过Workbooks.Add
创建新工作Workbooks.Add
Instead, you should: 相反,你应该:
SaveAs
method on the worksheet 在工作表上调用SaveAs
方法 It would look something like this, also modified to ensure file does not already exist. 它看起来像这样,也修改为确保文件尚不存在。 If file already exists, the MsgBox
alerts you and then procedure will exit without saving. 如果文件已存在, MsgBox
提醒您,然后过程将退出而不保存。
Sub SaveAs_CSV()
Dim SaveNAme$, SavePath$, csvFullName$
Application.ScreenUpdating = False
Application.DisplayAlerts = False
SaveNAme = Range("B2")
SavePath = Range("B3")
If Right(SavePath,1) <> Application.PathSeparator Then SavePath = SavePath & Application.PathSeparator
csvFullName = savePath & SaveNAme & ".csv"
If Dir(csvFullName) <> "" Then
'File already exists, alert the user and exit procedure
MsgBox csvFullname & " already exists! The file will not be saved as CSV.", vbInformation
GoTo EarlyExit
End If
ActiveSheet.SaveAs Filename:=csvFullName _
, FileFormat:=xlCSVWindows, CreateBackup:=False
Rows("1:4").EntireRow.Delete
Columns("A:D").AutoFit
ActiveWindow.Close
EarlyExit:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.