Save Copy as CSV MSDOS (Without closing/changing workbooks) - excel

I have a macro that saves the current workbook as CSV MSDOS format.
Here's my code:
Sub Save_CSV()
Dim Location, FileName As String
Location = "C:\Users\myawesomename\OneDrive\Desktop\GM MRP\"
FileName = Left(ActiveWorkbook.name, Len(ActiveWorkbook.name) - 5)
ActiveWorkbook.SaveAs FileName:= _
Location & FileName & ".csv", FileFormat:= _
xlCSVMSDOS, CreateBackup:=False
ActiveWorkbook.Save
End Sub
After I use this macro, I'm no longer working on the xlsv. Rather, I'm working on the CSV version with all the sheets still present. If I close the workbook without saving it, I can then open the CSV file and only the first sheet is present. It's fine that only the first sheet is present but I want it to save a separate CSV file (with the first sheet only present) while continuing to work on the XLSX file without opening the CSV at all. I'm not trying to save each sheet as a separate file.
I tried several things including changing "Activeworkbook.SaveAs" to "Activeworkbook.savecopyas" but I couldn't achieve the desired result.
Thank you,

Related

Transfer data range from worksheet as new csv file in dedicated directory [duplicate]

This question already has answers here:
Saving excel worksheet to CSV files with filename+worksheet name using VB [duplicate]
(5 answers)
Export each sheet to a separate csv file
(2 answers)
Closed 1 year ago.
Quite new to VBA coding, I have the following data in a worksheet called "int_151_schedule", I am trying to take the data that is in the range A4:AK16 and create a new csv from this in the following directory: '\Desktop\Test'
My code is depicted below but I am getting the error ID 1004, indicating that it is not saving it to the path directory successfully. I have seen similar questions to this but haven't had much success. Is there anything wrong with my code?
Sub CreateNewCSV()
Sheets("int_151_schedule").Copy
Application.DisplayAlerts = False
With ActiveWorkbook
.SaveAs Filename:="\Desktop\Test " & Range("A4:AK16").Value & ".csv"
.Close savechanges:=True
End With
Application.DisplayAlerts = True
End Sub
I think your code is trying to save the file with a filename of contents of your array, which may not be what you want to do.
You also need to include the entire file path with drive. (e.g. C:\
First copy the contents of A4:AK16 to a new workbook and then save this workbook as a *.csv file.
Try
Sub CreateNewCSV()
Range("A4:AK16").Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.SaveAs Filename:= _
"C:\Desktop\Test\myfilename.csv", FileFormat:= _
xlCSV, CreateBackup:=False
End Sub

Export more sheets as separate .csv files

I'm trying to export two sheet in two different csv file using the code presented below:
import_bt.SaveAs Filename:="D:\Temp\import_bt.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=False
import_brd.SaveAs Filename:="D:\Temp\import_brd.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=True
The code works fine but I've an issue, it saves also my entire file as the last .csv file named import_brd.
In order to be able to copy sheets, without changing the active document name, you cannot proceed as you tried. It will always save the sheet, but the workbook will be Saved As your last allocated (csv) name.
Try this code, please:
Sub testSaveSheetAsCSV()
Dim import_bt As Worksheet, import_brd As Worksheet, wb As Workbook
'I used dummy sheets name only for testing reason. Please, use your real ones:
Set import_bt = Sheets("Test") 'use here your necessary sheet
Set import_brd = Sheets("Teste") 'use here your necessary sheet
Set wb = Workbooks.aDD
import_bt.Copy Before:=wb.Worksheets(1)
wb.SaveAs fileName:=ThisWorkbook.path & "\import_bt.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=False
import_brd.Copy Before:=wb.Worksheets(1) 'it will save its first sheet
wb.SaveAs fileName:=ThisWorkbook.path & "\import_brd.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=True
wb.Close False
End Sub
It adds a new workbook, copy the sheet necessary to be transformed in CSV, before the existing first one of the newly created workbook and save it (AS CSV) after that. It repeats the steps for the second sheet and closes the temporary workbook.
If you need to avoid the warning regarding overwriting of the existing file(s) (if the case), the code can be adapted to avoid it. Only in case you want playing with the code, or updating the existing csv files with the last necessary ones.

Copy and paste an excel file with variable name

What I want to design is a file which can copy and paste a file in the active worksheet. However, this file will be updated daily and also change its name. Therefore, I'd like to refer to a dynamic name so to say.
Sub stackoverflow()
' copy workbook to new worksheet
Workbooks.Open Filename:= _
"/Documents/Documenten/movementreport202001075.xlsx"
Cells.Select
Selection.Copy
Windows("test").Activate
ActiveSheet.Paste
End Sub
For instance, the "20200107" can be "20200108.xlsx" tomorrow. So it is dependent on the date, time and seconds you download the report.
You can use the format function to put it into the format you want:
Workbooks.Open Filename:= "/Documents/Documenten/" & Format$(Date, "d.m.yyyy") & ".xlsx"
Seems like you would want to use a drive letter too tho...
Update:
It's the same concept (all you are doing is formatting the date and concatenating string values):
Workbooks.Open Filename:= "/Documents/Documenten/movementreport" & Format$(Date, "dmyyyy") & ".xlsx"
see how that works now?
I still say you would probably want to use a drive letter too tho...

Code being saved to formatted workbook

I have a template that user will open up, select the text file and VBA does all the magic. At the end of the code I have the SaveAs dialog box come up, user type in name and saves to appropriate location. I have this code sitting in a module of the main temmplate. The problem I have is the formatted file has the module in it where the code sits. I don't want that. I know I've figured this out before but today is not that day. Relevant code pasted below. I've tried changing the file formats, moving code to a worksheet. What am I missing/forgetting?
Filename = "WhateverName_"
SaveThiisFile = Application.GetSaveAsFilename(InitialFileName:=Filename, _
fileFilter:="Excel Files (*.xls), *.xls", _
FilterIndex:=1, Title:="Save As")
If ThisFile = False Then Exit Sub
ActiveWorkbook.SaveAs Filename:=SaveThisFile
ActiveWorkbook.Close (False)

Macro to export worksheets in .xlsx workbooks to tab-delimited .txt files won't work with .xlsm workbooks

Edit: I updated my code based on the comments, but get the same symptoms.
Edit 2: I updated the code, again, and I know that it works on a directory of .xlsx files. If I convert all of the .xlsm files to .xlsx files to drop the macros/code, then the code works great. Likely this problem is too localized.
Earlier today I learned how to loop over a folder of .xlsx files and export every sheet to a tab-delimited .txt file. My bigger goal is to loop over a folder of .xlsm files (whose macros aren't all on my machine) and write the data worksheets to .txt files.
Here's the modified code.
Sub exportsSheetsToTextForAll()
Application.AutomationSecurity = msoAutomationSecurityForceDisable
excelFiles = Dir(ThisWorkbook.Path & "\" & "Payout data*.xlsm")
fromPath = ThisWorkbook.Path
Do While Len(excelFiles) > 0
Debug.Print Files
Set oWb = Workbooks.Open(Filename:=fromPath & "\" & excelFiles)
Application.Run "exportSheetsToText", oWb
oWb.Close SaveChanges:=False
excelFiles = Dir
Loop
End Sub
Sub exportSheetsToText(iWb As Workbook)
For Each ws In iWb.Worksheets
ws.Copy
Set wb = ActiveWorkbook
textFile = Left(iWb.FullName, InStr(iWb.FullName, ".") - 1) & "-" & ws.Name & ".txt"
wb.SaveAs Filename:=textFile, FileFormat:=xlText
wb.Close SaveChanges:=False
Next ws
End Sub
I modified the answer to my first question due to the structure of the .xlsm files. Each .xlsm file has a data query worksheet ("REQUEST_TABLE") with cells for query entries and buttons for macros. Running the query generates new sheets ("Sheet1", "Sheet2", etc) with the data I want to export.
When I run the exportAllSheetsToText() macro it opens the first worksheet, but it starts with the data query worksheet ("REQUEST_TABLE"), saves it to a tab-delimited text file, and stops rather than proceeding through all of the worksheets. I thought that the macro would carry on through all of the sheets as is does with my original macro for looping over all workbooks and worksheets in a directory.
What changes when I run my macro on an .xlsm file? Do I need to strip these worksheets to their own .xlsx files first? Thanks!

Resources