Sunday, September 20, 2015

VBA Macro to Export Data from Excel Spreadsheet to CSV

Sub Export_CSV()

'***************************************************************************************
'author: kay cichini
'date: 26102014
'purpose: export current spreadsheet to csv.file to the same file path as source file
'
' !!NOTE!! files with same name and path will be overwritten
'***************************************************************************************


Dim MyPath As String
Dim MyFileName As String
Dim WB1 As Workbook, WB2 As Workbook

Set WB1 = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy

Set WB2 = Application.Workbooks.Add(1)
WB2.Sheets(1).Range("A1").PasteSpecial xlPasteValues

MyFileName = "CSV_Export_" & Format(Date, "ddmmyyyy")
FullPath = WB1.Path & "\" & MyFileName

Application.DisplayAlerts = False
If MsgBox("Data copied to " & WB1.Path & "\" & MyFileName & vbCrLf & _
"Warning: Files in directory with same name will be overwritten!!", vbQuestion + vbYesNo) <> vbYes Then
Exit Sub
End If

If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
With WB2
.SaveAs Filename:=FullPath, FileFormat:=xlCSV, CreateBackup:=False
.Close True
End With
Application.DisplayAlerts = True
End Sub

No comments:

Post a Comment