简体   繁体   中英

VBA to export data to CSV file (only values)

I would like to carry out the captioned task with the following codes modified from extendoffice.com (thank you).

Sub export_data_to_CSV()

Dim Rng As Range
Dim WorkRng As Range
Dim xFile As Variant
Dim xFileString As String
Dim LR As Long
LR = Application.WorksheetFunction.CountA(Worksheets("MAIN").Range("A1:A50001"))

Set WorkRng = Application.Selection
Set WorkRng = Worksheets("MAIN").Range("A2:J" & LR)


Application.ActiveSheet.Copy
Application.ActiveSheet.Cells.Clear
WorkRng.Copy Application.ActiveSheet.Range("A1")
Set xFile = CreateObject("Scripting.FileSystemObject")
xFileString = Application.GetSaveAsFilename("", filefilter:="Comma Separated Text (*.CSV), *.CSV")
Application.ActiveWorkbook.SaveAs Filename:=xFileString, FileFormat:=xlCSV, CreateBackup:=False

End Sub

The code works fine, however, it saves all formulas and even my button to the target file. What should I do to the code if I only want to save values to the target CSV file?

CSV files can't have formulas or buttons by definition. I think you're just seeing them in the currently open Excel instance, but if you were to open the newly saved CSV file, they would not be present.

To address your follow-up question:

If I want to close the target file instantly with the code, what lines should I add?

ActiveWorkbook.Close SaveChanges:=False

Here is some demo code. It:

  1. copies Sheet1 to a new workbook
  2. clears all formula cells in the clone ( copied ) worksheet
  3. saves the clone as .csv
  4. closes the clone workbook


Sub KopyKat()
'
    Sheets("Sheet1").Select 'move to sheet
    Sheets("Sheet1").Copy   'copy sheet to new workbook

    ActiveSheet.Cells.SpecialCells(-4123).Clear 'get rid of formulas

    'then save as .csv

    ActiveWorkbook.SaveAs Filename:="C:\Users\garys\Desktop\bk.csv", FileFormat _
        :=xlCSVUTF8, CreateBackup:=False
    ActiveWorkbook.Close 'close the new workbook

    ' the original workbook is now active again
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