Save Specific single sheet as .csv - vba

I have a very similar question as this post:
Save individual Excel sheets as CSV
My question differs in that I only need one sheet to be saved
This is the answer from that post
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.SaveAs "C:\docs\" & ws.Name & ".csv", xlCSV
Next
This code saves each worksheet to a specific folder and names the file the same as the worksheet. 2 problems I see:
1- The workbook you were currently working on becomes the very last worksheet the code saved. If you want to keep working on your workbook you have to open the original file. It would work better if a new workbook was opened and saved separately from the one that is being worked on.
2- It saves each worksheet. I only need to save one specific worksheet, i.e Sheet2
I found this other code but I am VERY new to VBA and only know how to create a macro, copy & paste code into it. I get error when I run the code.
Sub test()
Application.DisplayAlerts = False
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=strFullname, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
Hopefully I can get pushed in the right direction. Thanks!

strSourceSheet is the sheet which has the name/number of the sheet which you want to export
strFullname is the filename with path of the csv. As simple as that.
Now see this code
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=strFullname, _
FileFormat:=xlCSV, _
CreateBackup:=True
ActiveWorkbook.Close
Let's say I want to copy Sheet2 then I would write it as
Dim strSourceSheet As String
Dim strFullname As String
'~~> Change the below two lines as per your requirements
strSourceSheet = "Sheet2"
strFullname = "C:\Temp\MyCsv.Csv"
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=strFullname, _
FileFormat:=xlCSV, _
CreateBackup:=True
ActiveWorkbook.Close
Did you notice how we switch between ThisWorkbook and ActiveWorkbook. When you copy the sheet a new workbook is created and becomes active and hence to close that we use ActiveWorkbook
Hope this helps.

Related

Excel VBA execute code in newly created workbook

I'm trying to save one worksheet in my excel file to a new file, but without the formula's.
I have this code that is working to get the file saved:
Sub SaveInvoice()
'Create a filename based on invoicenumber
Dim FileName As String
FileName = Sheets("Sale").Range("C3").Value
'Copy the "Print" sheet
Worksheets("Print").Copy
With ActiveWorkbook
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
End Sub
This works like a charm, however I need to strip out the formula's so I googled and fount this piece of code:
ActiveSheet.Copy
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
And this works as well, however once I merge the two pieces of code together the whole function breaks.
With ActiveWorkbook
'Transform cells to values
ActiveSheet.Copy
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
This results in my base worksheet beeing stripped from formula's.
I need to know how I can call the function on the newle created workbook.
When copying a worksheet with no Destination excel creates a New Workbook, and the New Workbook with its only Worksheet are active.
EDIT: I just realized that in the final code these lines from the original code:
'Copy the "Print" sheet
Worksheets("Print").Copy
Were moved inside the
With ActiveWorkbook
That was previously referring to the New Workbook created by the Worksheet.Copy and that now refers to the Source Workbook
So let see what the Op's final code is actually doing:
Here the ActiveWorkbook is the [Source Workbook] and the ActiveSheet must be [Print]
With ActiveWorkbook
This copies the ActiveSheet creating a New Workbook with only one sheet
ActiveSheet.Copy
These lines are affecting the ActiveSheet [Print] in the [Source Workbook].
Not because of the With statement but because it's the one active
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
The commands within a With intended to affect object that it refers to must start with a dot [.]; however these lines are invalid because Cells and Range are not Methods nor Properties of the Workbook Object, thus en error would have been triggered.
With Statement
Executes a series of statements on a single object or a user-defined type.
(from the msdn.microsoft.com help)
This saves the Workbook referred by the With statement, which still has the formulas
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
Try this code:
Sub SaveInvoice_TEST_1()
'Create a filename based on invoicenumber
Dim FileName As String
With ThisWorkbook
FileName = .Sheets("Sale").Range("C3").Value
'Copy the "Print" sheet
.Worksheets("Print").Copy
End With
With ActiveWorkbook
Rem Replace Formulas with Values
.Sheets(1).UsedRange.Value = .Sheets(1).UsedRange.Value2
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
End Sub
Suggest to read the following pages to gain a deeper understanding of the resources used:
With Statement
Try something like the following. Read the help page for 'ActiveSheet.Copy' - note that it creates a new workbook and activates it
Dim MyWkbk as workbook
set MyWkbk = ActiveWorkbook
ActiveSheet.Copy
With ActiveWorkbook
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
'Save the file as new
.SaveAs FileName:="C:\" & FileName
'.close
End With
MyWkBk.activate
Thanks to #EEM the solution was found.
Here's the code I used:
Sub SaveInvoice()
Dim FileName As String
With ThisWorkbook
'Create a filename based on invoicenumber
FileName = .Sheets("Sale").Range("C3").Value
'Copy the "Print" sheet
.Worksheets("Print").Copy
End With
With ActiveWorkbook
'Replace Formulas with Values
.Sheets(1).UsedRange.Value = .Sheets(1).UsedRange.Value2
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
End Sub

opening and copy/pasting variable named file

I have the following vba code which opens a Folder, where i save the Excel files with certain names ("11.xlsm and "2.xlsm") and then open These files automatically and copy their Sheets called "data" and paste it to my masterworkbook "makrotochange".
ChDir _
"Z:\1000_Entwicklung\05_PROJECT\0558000_CFT\055800L_CFT_Projektleitung\99_Arbeitsordner PL\Tanverdi, Yigit\SAA"
Workbooks.Open Filename:= _
"Z:\1000_Entwicklung\05_PROJECT\0558000_CFT\055800L_CFT_Projektleitung\99_Arbeitsordner PL\Tanverdi, Yigit\SAA\11.xlsm"
Workbooks.Open Filename:= _
"Z:\1000_Entwicklung\05_PROJECT\0558000_CFT\055800L_CFT_Projektleitung\99_Arbeitsordner PL\Tanverdi, Yigit\SAA\2.xlsm"
Windows("makrotochange.xlsm").Activate
Windows("11.xlsm").Activate
sheets("data").Select
sheets("data").Move After:=Workbooks("makrotochange.xlsm").sheets(23)
Windows("2.xlsm").Activate
sheets("data").Select
sheets("data").Move After:=Workbooks("makrotochange.xlsm").sheets(24)
I want to be able to open any amount of variable named files which is in
"Z:\1000_Entwicklung\05_PROJECT\0558000_CFT\055800L_CFT_Projektleitung\99_Arbeitsordner PL\Tanverdi, Yigit\SAA"
and copy/paste it to my "makrotochange.xlsm" masterworkbook.
How can i do this ?
Untested, as i am currently unable to use Excel. However, using the information you provided, and the link #Mrig provided, i believe this could be the base for what you're looking for.
Sub LoopThroughFiles()
Dim StrFile As String
Dim WB As Workbook
Dim InputFilePath As String
InputFilePath = "Z:\1000_Entwicklung\05_PROJECT\0558000_CFT\055800L_CFT_Projektleitung\99_Arbeitsordner PL\Tanverdi, Yigit\SAA\"
StrFile = Dir(InputFilePath & "*")
Do While Len(StrFile) > 0
Set WB = Workbooks.Open(InputFilePath & StrFile)
WB.Activate
Sheets("data").Select
Sheets("data").Move After:=Workbooks("makrotochange.xlsm").Sheets(23)
StrFile = Dir()
Loop
End Sub
EDITED
Edited the code now that i am able to use Excel.
This will take all the files in the folder, open them, copy the "Data" sheet, and move it to after sheet 23 in your makrotochange.xlsm file.
A few points of interest though.
You need to make sure that your makrotochange.xlsm file is open to begin with.
You need to make sure all files have a sheet called "Data".
They will be pasted after Sheet 23. So the last file to be pasted in will be the one next to sheet 23.
Have fun

VBA Saving single sheet as CSV (not whole workbook)

I appreciate there are lots of entries like save individual excel sheets as csv
and Export each sheet to a separate csv file - But I want to save a single worksheet in a workbook.
My code in my xlsm file has a params and data sheet. I create a worksheet copy of the data with pasted values and then want to save it as csv. Currently my whole workbook changes name and becomes a csv.
How do I "save as csv" a single sheet in an Excel workbook?
Is there a Worksheet.SaveAs or do I have to move my data sheet to another workbook and save it that way?
CODE SAMPLE
' [Sample so some DIMs and parameters passed in left out]
Dim s1 as Worksheet
Dim s2 as Worksheet
Set s1 = ThisWorkbook.Sheets(strSourceSheet)
' copy across
s1.Range(s1.Cells(1, 1), s1.Cells(lastrow, lastcol)).Copy
' Create new empty worksheet for holding values
Set s2 = Worksheets.Add
s2.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
' save sheet
s2.Activate
strFullname = strPath & strFilename
' >>> BIT THAT NEEDS FIXIN'
s2.SaveAs Filename:=strFullname, _
FileFormat:=xlCSV, CreateBackup:=True
' Can I do Worksheets.SaveAs?
Using Windows 10 and Office 365
This code works fine for me.
Sub test()
Application.DisplayAlerts = False
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=strFullname, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
It's making a copy of the entire strSourceSheet sheet, which opens a new workbook, which we can then save as a .csv file, then it closes the newly saved .csv file, not messing up file name on your original file.
This is fairly generic
Sub WriteCSVs()
Dim mySheet As Worksheet
Dim myPath As String
'Application.DisplayAlerts = False
For Each mySheet In ActiveWorkbook.Worksheets
myPath = "\\myserver\myfolder\"
ActiveWorkbook.Sheets(mySheet.Index).Copy
ActiveWorkbook.SaveAs Filename:=myPath & mySheet.Name, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Next mySheet
'Application.DisplayAlerts = True
End Sub
You just need to save the workbook as a CSV file.
Excel will pop up a dialog warning that you are saving to a single sheet, but you can suppress the warning with Application.DisplayAlerts = False.
Don't forget to put it back to true though.
Coming to this question several years later, I have found a method that works much better for myself. This is because the worksheet(s) I'm trying to save are large and full of calculations, and they take an inconvenient amount of time to copy to a new sheet.
In order to speed up the process, it saves the current worksheet and then simply reopens it, closing the unwanted .csv window:
Sub SaveThisSheetInParticular()
Dim path As String
path = ThisWorkbook.FullName
Application.DisplayAlerts = False
Worksheets("<Sheet Name>").SaveAs Filename:=ThisWorkbook.path & "\<File Name>", FileFormat:=xlCSV
Application.Workbooks.Open (path)
Application.DisplayAlerts = True
Workbooks("<File Name>.csv").Close
End Sub
Here the Sheet and csv filename are hardcoded, since nobody but the macro creator (me) should be messing with them. However, it could just as easily be changed to store and use the Active Sheet name in order to export the current sheet whenever the macro is called.
Note that you can do this with multiple sheets, you simply have to use the last filename in the close statement:
Worksheets("<Sheet 1>").SaveAs Filename:=ThisWorkbook.path & "\<File 1>", FileFormat:=xlCSV
Worksheets("<Sheet 2>").SaveAs Filename:=ThisWorkbook.path & "\<File 2>", FileFormat:=xlCSV
[...]
Workbooks("<File 2>.csv").Close

How to use Excel .SaveAs but retain original sheet name

I am working with Excel 2010, and have a userform which will support various processing options (i.e. sort by predefined ranges, get statistics, and the dreaded 'export' (SaveAs). I want to allow the user to export one of the sheets as either CSV or XLSX.
The issue is when I use the SaveAs to save as a CSV, it renames the sheet to the filename I selected (minus the extension). I have searched for hours and have not found any place that provides a solution. I did find a Stack 5+ year old post, but it didn't have a solution (see How to stop renaming of excelsheets after running the save macro)
Any help would be appreciated! Thanks!
Here is the code:
Dim ws As Excel.Worksheet
Dim strSaveName As String
Dim strThisName As String
strThisName = ThisWorkbook.Path & ThisWorkbook.Name
strSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.csv), *.csv")
Set ws = Worksheets("Export")
ws.SaveAs Filename:=strSaveName, FileFormat:=xlCSV
'I do the following TO UNDO THE RENAME <GROAN> (for now just saving as 0.csv)
Sheets("0").Name = "Export"
' Then the following is to regain my original filename since I will continue working...
ws.SaveAs Filename:=strThisName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Use ws.Copy with no args beforehand then save the new workbook
e.g. adapt your code to be like:
Dim ws As Excel.Worksheet
Dim strSaveName As String
strSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.csv), *.csv")
Set ws = Worksheets("Export")
'Copy the ws to a new workbook
ws.Copy
'With the new wb:
With Workbooks(Workbooks.Count)
'Save and close the new workbook
.SaveAs Filename:=strSaveName, FileFormat:=xlCSV
.Close False
End With
p.s. I assume you have code to handle clicking Cancel on GetSaveAsFilename and just removed it for clarity in the question ;)

VBA - How to copy row in Excel from one workbook to another?

Despite many posts I have looked through being of along the same lines as my question, none of the answers satisfy what I am looking for. If you can link me to one I'd gladly read it.
I have a workbook with worksheets. For simplicity, let's say my workbook has a worksheet. And in my worksheet which is called "Sheet1", there is data in cells A1 to A4.
What I want my VBA code to do is:
Copy row 1 (or specifically cells A1 to A4) of Workbook 'A' into Range variable 'myRange'
Create a new workbook, let's call this one Workbook 'B'
Give Workbook 'B's default "sheet1" a new name to "Test Name"
Open Workbook 'B' (though I realise that VBA code "Workbooks.Add" opens a new book so this step may be redundant since Workbooks.Add covers half of point 2 and 3)
Paste 'myRange' into first row of 'Workbook B'
Save 'Workbook B' with name "Test Book" and a timestamp enclosed in square brackets. The file must also be of the file extension "xls"
Close 'Workbook B' and return to 'Workbook A'
What I have so far is this:
Sub OpenAndSaveNewBook()
'Declarations
Dim MyBook As String
Dim MyRange As Range
Dim newBook As Workbook
'Get name of current wb
MyBook = ThisWorkbook.Name
Set MyRange = MyBook.Sheets("Sheet1").Range("A1,F1")
'Create/Open new wb
newBook = Workbooks.Add
'Save new wb with XLS extension
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "/" & "TEST-BOOK", _
FileFormat:=xlNormal, CreateBackup:=False
'===NOTE: BEFORE THE FOLLOWING RUNS I NEED TO PERFORM ACTIONS ON CELLS VIA VBA ON
'===WORKBOOK 'A'. DOES THE NEWLY CREATE WORKBOOK BECOME THE PRIMARY/ACTIVE WORKBOOK
'===? AND SO THEN DO I NEED TO ACTIVATE WORKBOOK 'A'?
ActiveWorkbook.Close savechanges:=True
'Return focus to workbook 'a'
MyBook.Activate
End Sub
As you can see, I am lacking the code that will handle:
the pasting of my copied data to the new workbook
the changing of the new workbook's sheet1 name to something else
adding a timestamp to the filename string on save
Lastly, I have included a question in my code as I think I may have a misunderstanding of the ActiveWorkbook method. AFAIK when the code "Workbooks.Add" runs this becomes the Active Workbook, i.e. one with the focus. Does this effect how the VBA code running on Workbook 'A'? Does this mean that if I wanted to add code to manipulate cells of Workbook 'A' then I would need to use "MyBook.Activate" where 'MyBook' holds the string of Workbook 'A's actual title?
Any help will be greatly appreciated.
Thanks,
QF
Instead of copy pasting the way you mentioned above, you can directly do this. This will also negate the use of a variable.
MyBook.Sheets("Sheet1").Rows("1:4").copy _
newBook.Sheets("Sheet1").Rows("1")
EDIT
I just noticed an error with your code.
newBook = Workbooks.Add
This line will give you an error as you have to use Set
Your code can be written as
Option Explicit
Sub OpenAndSaveNewBook()
Dim MyBook As Workbook, newBook As Workbook
Dim FileNm As String
Set MyBook = ThisWorkbook
FileNm = ThisWorkbook.Path & "\" & "TEST-BOOK.xls"
Set newBook = Workbooks.Add
With newBook
MyBook.Sheets("Sheet1").Rows("1:4").Copy .Sheets("Sheet1").Rows("1")
'Save new wb with XLS extension
.SaveAs Filename:=FileNm, FileFormat:=xlNormal, CreateBackup:=False
.Close Savechanges:=False
End With
End Sub
MORE EDIT
Elaborating on the use of SET
I would recommend you to see this post.
LINK: Worksheets does not work
Avoid references to ActiveWorkbook in favour of explicit references wherever possible.
As you've found, it can be confusing knowing what's currently active, and you do not need to activate a workbook to manipulate it.
So you should be using
newBook.SaveAs...
newBook.Close...
Recorded macros tend to activate workbooks in order to work on them, but that's because that's the way a human who recorded them works! All activation really does is change focus.
The same applies to making selections and then manipulating the current selection; it's not necessary in VBA and tends to be slower than direct manipulation.
The awesome thing about Excel is the 'Record Macro' function. I started recording a macro and just followed the steps you outlined, then made a few minor modifications to the code that Excel provided as the recorded macro:
Range("A1:F1").Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Sheets("Sheet1").Name = "Test Name"
Application.CutCopyMode = False
myNewFileName = myPath & myTestName & "_" & Date & ".xls"
ActiveWorkbook.SaveAs Filename:=myNewFileName _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
The Date function returns the current system date. It is important to note that the square brackets that you wanted are not valid filename characters; Excel will throw an error if you try to use those.
Turn the macro-recorders on; carefully execute the steps you want; stop the recorder; "edit" the macro generated. Fix as you need to make the program you intend, e.g., to parameterize it.