I have a macro that works for one particular file.
How can I make it work for all my files? Specifically how do I change the name of the file so that it saves the file that is being opened?
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+m
'
Range("A:A,B:B").Select
Range("B1").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLineStacked
ActiveChart.SetSourceData Source:=Range( _
"'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B")
ChDir "D:\WayneCSV"
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub
With ActiveSheet.Shapes.AddChart
.ChartType = xlLineStacked
.SetSourceData Source:=Range( _
"'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B")
End With
ChDir "D:\WayneCSV"
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & *YourFileNameHere* &".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Replace the YourFileNameHere with the name you'd like to save the file with.
Or if you want to simply save the active workbook with the change
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.FullName, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
If you want to loop through all possible workbook or file inside of "D:\WayneCSV" just tell me what you mean by make it work for all my files? weather that means open excel sheets, or workbook, or all files with extension of *.xlsx inside of "D:\WayneCSV"
Edit:
Dim StrFile As String
StrFile = Dir("D:\WayneCSV\*.CSV") ' Looks up each file with CSV extension
Do While Len(StrFile) > 0 ' While the file name is greater then nothing
Workbooks.Open Filename:= "D:\WayneCSV\" & StrFile ' Open current workbook
ActiveSheet.Shapes.AddChart.Select ' Add a chart
ActiveChart.ChartType = xlLineStacked ' Add a chart type
ActiveChart.SetSourceData Source:=Range("$A1:$B1", Range("$A1:$B1").End(xlDown)) ' Set the source range to be the used cells in A:B on the open worksheet
With ActiveChart.Parent
.Height = .Height*1.5 'Increase Height by 50%
.Width = .Width*1.5 'Increase Width by 50%
End With
'Note the setting of the source will only work while there are no skipped blank if you
'have empty rows in the source data please tell me and i can provide you with another
' way to get the information
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & StrFile & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False ' Save file as excel xlsx with current files name
ActiveWorkbook.Close ' Close when finished before opening next file this can be removed if you'd like to keep all open for review at the end of loop.
StrFile = Dir ' Next File in Dir
Loop
Let me know if it works as I can't test without your folders and data. But it should work.
Check out this SO link
I think what you want to do is replace :="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx"
with ActiveWorkbook.FullName in ActiveWorkbook.SaveAs line
where it is written
Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx"
that's your filename you could replace it with ThisWorkbook.FullName it should work
So it should give you something like this.
Filename:=ThisWorkbook.FullName,
Also I don't understand that part
ChDir "D:\WayneCSV"
Why put the path then the full name
I'm more an access programmer than an excel one so I could be wrong.
Your macro, from what I can tell, is adding a chart based off of some data and saving the sheet.
That is a very specialized Macro, but you would need to change the directory as others listed to a directory on your local drive but you also need to find out where the data you are creating a chart for is being stored.
Sub Macro1()
' ' Macro1 Macro ' ' Keyboard Shortcut: Ctrl+m ' '<<< This is the naming convention and hotkey if you goto Tools > Macros in Excel 2003 or Developer > Macros in 2010
'Range("A:A,B:B").Select '<<< This is where you are selecting all data in columns A and B and is not needed so I commented it out
'Range("B1").Activate '<<< This code is 'activating' a cell, but not sure why, so I commented it out as it should not be needed
ActiveSheet.Shapes.AddChart.Select '<<< You are adding a chart here
ActiveChart.ChartType = xlLineStacked '<<<Defining a chart type
ActiveChart.SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") '<<< Setting it's source data from a worksheet called 'cwapp5_MemCPU-Date-Mem' with header information from Column B and Data from Column A
ChDir "D:\WayneCSV"
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False '<<< You are saving a copy of your workbook
End Sub
To make this work for other workbooks you need to rename all of the ranges to where your data is, rename the tabs to what you have your tabs named, and rename the WorkBook to what you want it saved as and where.
Related
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
So i have this VBA at work, that I made a while ago. It used to work perfectly, but as of today it will not save my file after it opens the Save as window. It just goes to the MsgBox ive given it.
At first the problem was that LDate = Date somehow started returning the date with a forward slash. Ive fixed this by adding a format for LDate. But the bigger problem remains. No matter what i do, what code i remove or add, what name i write manually, the file wont save in any folder i give it.
Sub Export()
'
' Export Macro
'
' copy range from work workbook, create a new workbook and paste selection
Sheets("NewTemplate").Range("A1:M29").Copy
Workbooks.Add
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveSheet.Paste
' rename active sheet and active workbook
ActiveSheet.Name = "Create"
ActiveWorkbook.Windows(1).Caption = "Newly Generated Table"
Range("A1").Select
Application.CutCopyMode = False
' open Save As window, set file save name to custom prefix + date
Dim IntialName As String
Dim fileSaveName As Variant
InitialName = "Import_Feature_Values_"
Dim LDate As String
LDate = Date
LDate = Format(Now, "dd_mm_yyyy")
fileSaveName = Application.GetSaveAsFilename(FileFilter:= _
"Microsoft Excel Macro- Enabled Worksheet (*.xlsm), *.xlsm", InitialFileName:=InitialName & LDate)
'error box if filesavename fails
If fileSaveName <> False Then
MsgBox "Failed to Save as " & fileSaveName
End If
'
End Sub
GetSaveAsFilename does not save a file.
It only does what the function name says: Get a SaveAs filename from the dialog box.
So your variable fileSaveName just contains a file path and file name that was chosen in the dialog box, and you still need to save the file yourself.
Fore example to save the current workbook (that workbook code is running at) with the chosen filename:
ThisWorkbook.SaveAs Filename:=fileSaveName
or for the active workbook (that workbook that is on top):
ActiveWorkbook.SaveAs Filename:=fileSaveName
For macro enabled files define a file format according to XlFileFormat-Enumeration:
ActiveWorkbook.SaveAs Filename:=fileSaveName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
I have VBA where the user fills out a template, then saves as .XLSM and PDF.
The .XLSM saves as the entire workbook, but the PDF is only 2 worksheets. Both files are named after a variable cell in the workbook and a file location is suggested, but can be changed by the user.
Everything works until the user is warned that they are overwriting an existing file. If they select "no" or "cancel," then they get an error. Ideally, I would like for the sub to just exit and neither the PDF or .XLSM is saved. I have tried On Error, but cannot get the whole thing to work. Other solutions seem to take away some functionality (variable file name, different sheets printing/saving, initial file location, etc.).
Below is my code if anyone can help:
Sub SaveToPDF2()
Dim strFilename As String
Dim rngRange As Range
Dim fileSave As FileDialog
Set fileSave = Application.FileDialog(msoFileDialogSaveAs)
'Considering Sheet1 to be where you need to pick file name
Set rngRange = Worksheets("template").Range("b3")
'Create File name with dateStamp
strFilename = rngRange.Value & ".process." & Format(Date, "mm.dd.yyyy")
With fileSave
' Your default save location here
.InitialFileName = "U:\221 Released Drawings\" & strFilename
If .Show = -1 Then
ActiveWorkbook.SaveAs filename:=strFilename & ".xlsm", FileFormat:=52
ThisWorkbook.Sheets(Array("process", "signoff")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=strFilename _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
Else: Exit Sub
End If
End With
End Sub
Try inserting the next code line, just before With fileSave:
If Dir(strFilename & ".xlsm") <> "" then Exit Sub
If such a file already exists, the code is exited on the above inserted line...
Background:
I have two workbooks in the same directory with different sheets in each one of them.
I would like to open book2.xlsx, execute a VBA, to copy the whole content from "sheet1" in book1.xls. After this, the book1.xls should be closed automatically.
I have a code, which is moving the content next to a sheet, then I have to rename this sheet to the desired one. The problem with this is one is I the formulas in the other sheet will not work as desired. The code is as follows,
Sub XLVBACopyFiles()
Dim MonthlyWB As Variant
Dim FileName As String
FileName = ActiveWorkbook.Name
Path = ActiveWorkbook.Path & "\"
Application.DisplayAlerts = False
Application.EnableEvents = False
'Copy the sheet1 next to sheet2 in the current workbook
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
Sheets(Array("sheet1")).Move After:=Workbooks( _
FileName).Sheets("sheet2")
Application.EnableEvents = True
Application.DisplayAlerts = True
Workbooks(FileName).Save
' Workbooks(FileName).Close
End Sub
Any help with this would be highly appreciated.
If what you want , according to your comment above, is paste the content to "sheet2 itself", update the code above :
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
**Sheets(Array("sheet1")).Move After:=Workbooks( _
FileName).Sheets("sheet2")**
to
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
'Next 2 lines will select the range of content to be copied, and CTRL+C it. Edit it to your desire range
Range("A1:A5").Select
Selection.Copy
Sheets("Sheet2").Select
Range("A1").Select ' In this line you should choose which cell to start pasting
ActiveSheet.Paste
Also, to close workbook, use:
Workbooks("book1.xls").Close SaveChanges:=True
Pay attention to SaveChanges option, choose True/False if you want to save or not this workbook
I am using an Excel Macro that detects two worksheets and writes them to CSV format in their current SharePoint directory. However, upon executing the macro, it proceeds to open the newly created files within the same workbook and gives me the following error:
Run-time error '1004':
Sorry, we couldn't find C:\ProgramFiles(x86)\Google\Chrome\Application...
Is it possible it was moved, renamed or deleted?
Can I perform the "Save As" without opening the new file and avoiding the given error?
To be clear, it performs the core function just fine, as the new CSV files are properly written to the Sharepoint folder, I simply want to avoid the error message.
Macro code is as below:
Sub Export()
'
' Export Macro
' Export Rules and Privileges to 'Rules.csv' and Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.Activate
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.Activate
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Range("B9").Select
Application.Run "RulesWorkbook.xlsm!Export"
Range("B4").Select
End Sub
Thank you to FreeMan for the solution in getting rid of the error message. While I did not figure out how to prevent Excel from opening the newly generated programs, I was able to side-step that by closing the workbook upon macro execution. Updated code for the macro is below:
Sub Export()
'
' Export Macro
' Export SecurityRules and Privileges to 'Rules.csv' and 'Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub