Exporting sheet as csv - excel

i am trying to export a sheet from my Excel file as a csv.
I am getting the error
Method SaveAs of Object Workbook Failed`
on my SaveAs line.
I notice as this code creates a new workbook, it has several blank default sheet tabs, would this be causing the issue?
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Load check data") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
Path = ThisWorkbook.Sheets("Input").Range("B15") & "estload_" & ThisWorkbook.Sheets("Input").Range("F1") & ".csv"
Debug.Print Path
wbkExport.SaveAs Filename:=Path, FileFormat:=xlCSV, CreateBackup:=True
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
Edit to exclude WbkExport variable, replace with ThisWorkbook and ActiveWorkbook.
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Dim Path As String
Set shtToExport = ThisWorkbook.Worksheets("Load check data") 'Sheet to export as CSV
'Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
Path = ThisWorkbook.Sheets("Input").Range("B15") & "estload_" & ThisWorkbook.Sheets("Input").Range("F1") & ".csv"
Debug.Print Path
ActiveSheet.SaveAs Filename:=Path, FileFormat:=xlCSV, CreateBackup:=True
Application.DisplayAlerts = True
'wbkExport.Close SaveChanges:=False

The previous comments are correct. A simple procedure would be:
Public Sub ExportWorksheetAndSaveAsCSV()
'Simple copy of sheet content as csv file
Dim NameSheet As String
Dim PathNameCsv As Variant
'Change names & Output Path
NameSheet = "MySheet"
PathNameCsv = "D:\Documents\MyCsv"
Set shtToExport = ThisWorkbook.Worksheets(NameSheet) 'Sheet to export as CSV
Application.DisplayAlerts = False 'Possibly overwrite without asking
shtToExport.SaveAs Filename:=PathNameCsv, FileFormat:=xlCSV, CreateBackup:=True
Application.DisplayAlerts = True
'When saving the sheet as csv, _
'by default its name is changed to the name of the csv.
'Here you restore your name
With shtToExport
.Name = NameSheet '
End With
End Sub

Related

Export csv separated by columns

I have an Excel with several sheets I want to export to csv delimited by columns.
When I run the code, it exports the files to csv but comma delimited, not column delimited as I export in csv.
Any help would be appreciated.
Sub SaveShtsAsBook()
Dim Sheet As Worksheet, SheetName$, MyFilePath$, N&
MyFilePath$ = ActiveWorkbook.path & "\" & _
Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5)
With Application
.ScreenUpdating = False
.DisplayAlerts = False
' End With
On Error Resume Next '<< a folder exists
MkDir (MyFilePath & "_csv") '<< create a folder
For N = 1 To Sheets.Count
Sheets(N).Activate
SheetName = ActiveSheet.Name
Cells.Copy
Workbooks.Add (xlWBATWorksheet)
With ActiveWorkbook
With .ActiveSheet
.Paste
.Name = SheetName
[A1].Select
End With
'save book in this folder
.SaveAs ThisWorkbook.path & "\_csv\" & SheetName & ".csv", FileFormat:=xlCSV
.Close SaveChanges:=True
End With
.CutCopyMode = False
Next
End With
Sheet1.Activate
End Sub
Thanks!
Edit: Screenshot that clarifies my problem.
https://imgur.com/a/mPn997B
Define FileFormat as xlText and the file will be TAB delimited, which you obviously are looking for.
f.ex.:
Private Sub CommandButton1_Click()
Dim wb As Workbook
Set wb = ActiveWorkbook
wb.SaveAs "c:\tmp\tabtest.csv", xlText
End Sub

How to save files in a loop to xlsm macro enabled format?

I have the following code that loops through files and saves them as new files.
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wbTarget As Workbook
Dim wsTarget As Worksheet
Dim wsHide1 As Worksheet 'Declare Sheets to hide'
Dim wsHide2 As Worksheet
Dim wsHide3 As Worksheet
Dim wsHide4 As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
'Master workbook row that needs to be updated with source data'
rowTarget = 9
'Source files location'
Const FOLDER_PATH = "T:\SAMPLE DATA\1 - Split Raw Files\"
'loop through the Excel files in the folder'
sFile = Dir(FOLDER_PATH & "*.xls*")
'open template'
Const MASTER = "T:\SAMPLE DATA\ V7 Template\Tool Template V7.xlsm"
Set wbTarget = Workbooks.Open(MASTER)
Set wsTarget = Sheets("DATABASE") 'Target sheet of where data from source needs to be inserted'
'Sheets to hide'
Set wsHide1 = Sheets("Office Use Only1")
Set wsHide2 = Sheets("Office Use Only2")
Set wsHide3 = Sheets("Office Use Only3")
Set wsHide4 = Sheets("Office Use Only4")
wsTarget.Visible = xlVeryHidden
wsHide1.Visible = xlVeryHidden
wsHide2.Visible = xlVeryHidden
wsHide3.Visible = xlVeryHidden
wsHide4.Visible = xlVeryHidden
Do While sFile <> ""
' read source
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile) ' update links, readonly
Set wsSource = wbSource.Sheets(1)
' create target'
'wsTarget.Name = Replace(sFile, ".xlsx", "")'
wsTarget.Name = "DATABASE"
wsTarget.Unprotect "Password"
wsTarget.Range("A" & rowTarget).Resize(1, 364) = wsSource.Range("A2:MZ2").Value
wbTarget.SaveAs "T:\SAMPLE DATA\2 -Final Files\" & sFile & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
CreateBackup:=False
wsTarget.Protect "Password"
Application.DisplayAlerts = False 'Remove pop up messages'
wbSource.Close False
sFile = Dir
wsTarget.Visible = xlVeryHidden
wsHide1.Visible = xlVeryHidden
wsHide2.Visible = xlVeryHidden
wsHide3.Visible = xlVeryHidden
wsHide4.Visible = xlVeryHidden
Loop
wbTarget.Close False
End Sub
However the files keep saving as xlsx files in the loop and not macro enabled files with xlsm format. I also see that the files are saved with this type "Microsoft Excel 97-2003 Worksheet".. This format is supposed to be Microsoft macro enabled workbook as i use FileFormat:=xlOpenXMLWorkbookMacroEnabled.
Also how do i remove this pop up when i try to open the generated files above ? I tried to use Application.DisplayAlerts = False. However this doesn't seem to work.
Save File in Another Format
When changing the format of a file, you have to change both, its extension and the FileFormat parameter.
Also, note that column MZ is column 364, not 347.
Dim NewName As String
NewName = "T:\SAMPLE DATA\2 - Files\" & "test- " & sFile
NewName = Left(NewName, InStrRev(NewName, ".")) & "xlsm"
Application.DisplayAlerts = False 'Remove pop up messages'
wbTarget.SaveAs NewName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
CreateBackup:=False
wsTarget.Protect "Password"
wbSource.Close False
Application.DisplayAlerts = True

Merge specific workbooks into one

Sub MergeWorkbooks()
Dim Path As String
Dim FileName As String
Dim ws As Worksheet
Dim wb As Workbook
Application.EnableEvents = False
Application.ScreenUpdating = False
Path = "C:\Users\Name\Documents\Data\"
FileName = Dir(Path & "\*.xls", vbNormal)
Do Until FileName = ""
Set wb = Workbooks.Open(FileName:=Path & "\" & FileName)
For Each ws In wb.Worksheets
ws.Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)
Next ws
wb.Close False
FileName = Dir()
Loop
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I have 2 workbooks in same directory. Workbook 1 contain sheet A only and Workbook 2 contains sheets B and C. How can I merge sheet A and sheet C to my current workbook?
Make sure you open your source workbooks and then use the Worksheet.Move method or the Worksheet.Copy method to move or copy them into your current workbook.
Dim SourceWb1 As Workbook
Set SourceWb1 = Workbooks.Open(FileName:="C:\Path\To\Your\workbook1.xls")
SourceWb1.Worksheets("Sheet A").Move After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
Dim SourceWb2 As Workbook
Set SourceWb2 = Workbooks.Open(FileName:="C:\Path\To\Your\workbook2.xls")
SourceWb2.Worksheets("Sheet C").Move After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
If you used the .Move method make sure you don't forget to save your source workbooks:
SourceWb1.Close SaveChanges:=True
SourceWb2.Close SaveChanges:=True
If you used the .Copy method close them without saving:
SourceWb1.Close SaveChanges:=False
SourceWb2.Close SaveChanges:=False

How to save excel file in .bat?

I have this Code in Macro that i use to save files in csv. Is it possible now that i save this file in .bat Format ?
This is the Code i use :
Public Sub Export_File_as_CSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Export")
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False
wbkExport.SaveAs Filename:="C:\Users\" & Environ("Username") & "\Desktop\User_Tableau.csv", FileFormat:=xlCSV, Local:=True
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
Sheets("Export").Select
Range("A1").Select
End Sub
Otherwise i have to save it in Excel and then again to convert in .txt file and then in .bat file. I try to automate all this steps with macro and save it .bat file.
Your help is much appriciated !
Thank you
Just if someone Needs it in the future, i found the solution ! Apparently i was really close.
This is the changes i made and it worked.
Code :
Public Sub Export_File_as_BAT()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
'Call Artifficial_Groups
'Call filterout_for_export
'Call RemoveDuplicates
'Call Allocate_BEZ
Set shtToExport = ThisWorkbook.Worksheets("Export")
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False
wbkExport.SaveAs Filename:="C:\Users\" & Environ("Username") & "\Desktop\User_Tableau.bat", FileFormat:=xlTextPrinter, Local:=True
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
Sheets("Export").Select
Range("A1").Select
End Sub

Trying to copy a table to csv file and name it using original file name

I'm new to VBA and stuck on an issue. I'm trying to copy a table to a .csv file and I want the end result to contain the original .xlsm name & the table name and date/time. I've successfully pieced together code to export the table to .csv with the table name and date/time but I'm struggling to get the file mane in there. I get the following error "Method 'SaveAs' of object'_Workbook' failed"
Below is what I have, any help would be great!
Sub ExportTableBanquetEarnings()
Application.ScreenUpdating = False
Sheets("BanquetEarnings").Visible = True
Sheets("BanquetEarnings").Select
Dim wb As Workbook, wbNew As Workbook
Dim ws As Worksheet, wsNew As Worksheet
Dim wbNewName As String
Dim wbCurrent As String
wbCurrent = ThisWorkbook.FullName
Set wb = ThisWorkbook
Set ws = ActiveSheet
Set wbNew = Workbooks.Add
With wbNew
Set wsNew = wbNew.Sheets("Sheet1")
wbNewName = ws.ListObjects(1).Name
ws.ListObjects(1).Range.Copy
wsNew.Range("A1").PasteSpecial Paste:=xlPasteAll
.SaveAs Filename:="F:\admin\Report Databases\BanquetTipouts" & "\" &
wbCurrent & wbNewName & Format(Now, "yyyymmdd_hhmm") & ".csv", _
FileFormat:=xlCSVMSDOS, CreateBackup:=False
End With
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
ActiveWorkbook.RefreshAll
Sheets("BanquetEarnings").Visible = False
Sheets("Blank Cost Sheet").Select
Workbooks.Open "F:\Function Agreements\Cost Sheets M\Payroll Report -
V2.xlsm"
End Sub
The below code will show the path of that Workbook
wbCurrent = ThisWorkbook.FullName
I think what you meant to use is...
wbCurrent = ThisWorkbook.Name
Also, I think another issue might be the Now method, it should be as Now()

Resources