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

后端 未结 6 1285
一个人的身影
一个人的身影 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:03

    Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:

    1. it exports just the hardcoded sheet named "Sheet1";
    2. it always exports to the same temp file, overwriting it;
    3. it ignores the locale separation char.

    To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.

    Option Explicit
    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        
    
        Dim Change below to "- 4"  to become compatible with .xls files
        MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
         
        Application.DisplayAlerts = False
        TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
        TempWB.Close SaveChanges:=False
        Application.DisplayAlerts = True
    End Sub
    

    There are still some small thing with the code above that you should notice:

    1. .Close and DisplayAlerts=True should be in a finally clause, but I don't know how to do it in VBA
    2. It works just if the current filename has 4 letters, like .xlsm. Wouldn't work in .xls excel old files. For file extensions of 3 chars, you must change the - 5 to - 4 when setting MyFileName.
    3. As a collateral effect, your clipboard will be substituted with current sheet contents.

    Edit: put Local:=True to save with my locale CSV delimiter.

提交回复
热议问题