简体   繁体   中英

How can I save selected Excel worksheets as separate csv files, overwriting existing csv files with no dialogue?

I have code that saves ALL the worksheets in a workbook to csv files.
What I would like to do instead is to save only certain selected worksheets (selected by worksheet name). I would also like to leave the original excel file unchanged and still open. I would like to write over any pre-existing csv files automatically (no warning dialogue boxes)

Here is the code I am using so far:

Sub ExportWkshtCSV()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long
Application.DisplayAlerts = False

 CurrentWorkbook = ThisWorkbook.FullName
 CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook

      SaveToDirectory = "V:\whereIsavetheCSVs\"

      For Each WS In ThisWorkbook.Worksheets
          WS.SaveAs SaveToDirectory & WS.Name, xlCSV
      Next

 Application.DisplayAlerts = True

You might try this.

Const WsNames As String = "Sheet1,Sheet2,Sheet3,Sheet14,Sheet9"
Dim Ws          As Worksheet

For Each Ws In ThisWorkbook.Worksheets
    With Ws
        If InStr(1, WsNames, .Name, vbTextCompare) Then
            .SaveAs SaveToDirectory & .Name, xlCSV
        End If
    End With
Next Ws

Watch out for shorter names that might be included in longer ones. If this is an issue you may have to loop through all names to find a match. It's very fast. No problem in the execution. It would just take 3 extra lines of code to set up.

Here is the final code I ended up using

Dim CurrentFormat As Long

CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat

SaveToDirectory = "V:\WhereIsavedIt\"

Application.DisplayAlerts = False

Const WsNames As String = "Nameofsheet,Nameofothersheet"
Dim Ws          As Worksheet

For Each Ws In ThisWorkbook.Worksheets
    With Ws
        If InStr(1, WsNames, .Name, vbTextCompare) Then
            .SaveAs SaveToDirectory & .Name, xlCSV
        End If
    End With
Next Ws
  
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
 
Application.DisplayAlerts = True

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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