简体   繁体   English

文件保存为CSV格式iin excel vba

[英]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方法,因此无需执行以下操作:

  1. Create new workbook via Workbooks.Add 通过Workbooks.Add创建新工作Workbooks.Add
  2. Copy range of cells from current workbook 从当前工作簿复制单元格范围
  3. Paste copied selection in to the new workbook from (1) 从(1)将复制的选择粘贴到新工作簿
  4. Save the new workbook from (1) 保存新工作簿(1)

Instead, you should: 相反,你应该:

  1. Invoke the SaveAs method on the worksheet 在工作表上调用SaveAs方法
  2. Remove the rows (1-4) which you don't copy in the previous code 删除您在上一代码中未复制的行(1-4)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM