Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

后端 未结 6 1301
一个人的身影
一个人的身影 2020-11-28 08:39

There are a lot of questions here to create a macro to save a worksheet as a CSV file. All the answers use the SaveAs, like this one from SuperUser. They basically say to cr

6条回答
  •  甜味超标
    2020-11-28 09:27

    Here is a slight improvement on the this answer above taking care of both .xlsx and .xls files in the same routine, in case it helps someone!

    I also add a line to choose to save with the active sheet name instead of the workbook, which is most practical for me often:

    Sub ExportAsCSV()
    
        Dim MyFileName As String
        Dim CurrentWB As Workbook, TempWB As Workbook
    
        Set CurrentWB = ActiveWorkbook
        ActiveWorkbook.ActiveSheet.UsedRange.Copy
    
        Set TempWB = Application.Workbooks.Add(1)
        With TempWB.Sheets(1).Range("A1")
            .PasteSpecial xlPasteValues
            .PasteSpecial xlPasteFormats
        End With
    
        MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, InStrRev(CurrentWB.Name, ".") - 1) & ".csv"
        'Optionally, comment previous line and uncomment next one to save as the current sheet name
        'MyFileName = CurrentWB.Path & "\" & CurrentWB.ActiveSheet.Name & ".csv"
    
    
        Application.DisplayAlerts = False
        TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
        TempWB.Close SaveChanges:=False
        Application.DisplayAlerts = True
    End Sub
    

提交回复
热议问题