将多个工作表导出为CSV并指定保存文件夹

时间:2016-03-23 10:41:41

标签: excel vba excel-vba csv

我已经让这个宏工作得非常漂亮,但是它会不时地将导出的工作表保存到我工作的最后一个文件夹中,而不是我想要的特定文件夹。如何指定文件夹他们应该进去吗?

Sub asdf()
Dim ws As Worksheet, newWb As Workbook

Application.ScreenUpdating = False
For Each ws In Sheets(Array("sheet1", "sheet2", "sheet3"))
   ws.Copy
   Set newWb = ActiveWorkbook
   With newWb
      .SaveAs ws.Name & ".csv", xlCSVWindows
      .Close (False)
   End With
Next ws
Application.ScreenUpdating = True

End Sub

3 个答案:

答案 0 :(得分:1)

您需要在代码中指定要保存的位置。

试试这个。

.SaveAs FileName:="C:\OutputFilepath\" & ws.Name & ".csv", FileFormat:=xlCSV, CreateBackup:=False

答案 1 :(得分:1)

替换此行

.SaveAs ws.Name & ".csv", xlCSVWindows

使用

.SaveAs "D:\MyFolder\" & ws.Name & ".csv", xlCSVWindows

将“D:\ MyFolder \”更改为您想要的路径。

答案 2 :(得分:1)

添加包含文件夹完整路径的字符串类型var。在以下示例中,我将使用临时目录。

Sub asdf()

    Dim ws As Worksheet, newWb As Workbook, fp as string

    fp = environ("TEMP") & Chr(92)
    'could be something like
    'fp = environ("USER") & "\desktop\"

    Application.ScreenUpdating = False
    For Each ws In Sheets(Array("sheet1", "sheet2", "sheet3"))
       ws.Copy
       Set newWb = ActiveWorkbook
       With newWb
          .SaveAs fp & ws.Name, xlCSVWindows   'add the path, let saveas add the extension
          .Close savechanges:=False
       End With
    Next ws
    Application.ScreenUpdating = True

End Sub