Vba changing directory to save - excel

I'd like to save a file in a directory whose name changes according to the name of the Previous Month. Here is the code:
name_month = MonthName(Month(Date) - 1)
Set Newbook = Workbooks.Add
With Newbook
.Title = "TESO1"
.SaveAs Filename:="C:\Users\ee31264\Desktop\Mensile Automat\name_month \send\TESO1.xlsx"
End With
Newbook.Close
unfortunately the name_month i wrote VBA doesn't read what I mean!

That's because you need to tell Excel if what you say to it should be read as a variable or as string of text. Using "" says it is string of text and should not be evaluated.
Use this:
Filename:="C:\Users\ee31264\Desktop\Mensile Automat\" & name_month & "\send\TESO1.xlsx"
Also remember that in newer versions of Excel you also have to specify file format by using FileFormat:=51 (xlsx, use 52 for xlsm).

Related

VBA Excel save .xlsx file with the flexible name

I would like to save my file with the flexible name, which will change as the cell value changes.
The one answer is here:
Save a file with a name that corresponds to a cell value
however, I want also some fixed part of the name, which won't change unlike the part described in the query above.
Basing on this solution I tried to write something as follows:
Sub Save ()
Dim name As String, Custom_Name As String
name = Range("A2").Value
Custom_Name = "NBU" & name & "- Opportunity list.xlsx"
ActiveWorkbook.SaveAs Filename:=Custom_Name
In the effect, I am getting an error:
This extension cannot be used with the selected file type. Change the file extension in the File name text box or select a different type file by changing the Save as type.
I would like to have this file in the .xlsx extension.
Excel VBA - save as with .xlsx extension
The answer above doesn't really match to my situation.
It will be vital to remove all form control buttons in the newly saved file, when possible.
Thanks & Regards,
End Sub
There is no action in the routine listed to save the file. It just simply takes the contents of a cell and creates a string with wrapped values.
I am not totally sure of what your goal is, but you need to add the action from the second link you provided. Workbook.SaveAs Method.
See the code below for a working example that I created to test.
Public Sub Save()
Dim name As String, Custom_Name As String
name = Range("A2").Value
Custom_Name = ThisWorkbook.Path & "\" & "NBU" & name & " - Opportunity list.xlsx"
'Disable alert when saving
Application.DisplayAlerts = False
'Save the workbook.
ActiveWorkbook.SaveAs Filename:=Custom_Name, FileFormat:=51
End Sub
You should note that after this code has executed, you will now be in the newly created file. This is not an export.
Test this and let me know if you have any questions. There are a few things that seem to be unnecessary in your code, but we can address those if you find this answers your first issue.
Edit:
I would also call out specifically then worksheet with the range as well.
name = Worksheets("Sheet1").Range("A2")
You said the file name is 'Opportunity v1.0.xslm'. Would it have macros? My version of Excel complains about using .xlsx if there is code in the workbook.

Excel VBA code is not supporting to save a PPT at custom location with custom name

I am currently trying to write a short Excel VBA code which 1) create, 2) edit 3) save and 4) close a PowerPoint Presentation.
This can be done using the standard code which saves a file at a hard coded location. However, I am trying to write code in this way that it will pop-up two input boxes and will ask for your 1) custom name of file and 2) custom location where you want to save the file.
Code that I have trying to write is not giving any error message, but it is doesn't saving the file as well.
Sub Save_Presentation_at_custom_location()
Dim pPres As PowerPoint.Presentation
Set pApp = CreateObject("Powerpoint.Application")
pApp.Visible = True
Set pPres = pApp.Presentations.Add
pPres.Slides.Add 1, ppLayoutTitle
Filename = Application.InputBox("FileName") & ".PPTX"
Path = Application.InputBox("Path") & "\"
pPres.SaveAs Filename:="Path" & "FileName", FileFormat:=ppSaveAsDefault
pPres.Close
End Sub
Your issue is that you saved the strings with ""
Change:
pPres.SaveAs Filename:="Path" & "FileName", FileFormat:=ppSaveAsDefault
pPres.Close
to
pPres.SaveAs Filename:=Path & FileName, FileFormat:=ppSaveAsDefault
pPres.Close
Also your dimensions Filename, Path and pApp are not declared on the code you showed but I guess you did it in your real code

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

I have an Excel Workbook that on form button click I want to save a copy of the workbook with the filename being the current date.
I keep trying the the following
ActiveWorkbook.SaveAs ("\\filePath\FormFlow To MSExcel\" & Left(Now(), 10)) but am receiving Run-time error '1004': Method 'SaveAs' of object'_Workbook' failed.
Can anyone assist me with this? I'm still very new to developing for Excel.
Most likely the path you are trying to access does not exist. It seems you are trying to save to a relative location and you do not have an file extension in that string. If you need to use relative paths you can parse the path from ActiveWorkbook.FullName
EDIT:
Better syntax would also be
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlWorkbookNormal
Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'
Stop recording and you can start inspecting your code.
I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"
Option Explicit
Sub SaveFile()
Dim fdate As Date
Dim fname As String
Dim path As String
fdate = Range("A1").Value
path = Application.ActiveWorkbook.path
If fdate > 0 Then
fname = "Event " & fdate
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
MsgBox "Chose a date for the event", vbOKOnly
End If
End Sub
Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!
It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:
With someWorkbook
.SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
End With
OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.
xlExcel8 = 56 is the .xls format
xlExcel12 = 50 is the .xlsb format
xlOpenXMLWorkbook = 51 is the .xlsx format
xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format
xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.
I successfully use the following method in one file,
But come up with exactly the same error again...
Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
I was struggling, but the below worked for me finally!
Dim WB As Workbook
Set WB = Workbooks.Open("\\users\path\Desktop\test.xlsx")
WB.SaveAs fileName:="\\users\path\Desktop\test.xls", _
FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
Dim NuevoLibro As Workbook
Dim NombreLibro As String
NombreLibro = "LibroPrueba"
'---Creamos nuevo libro y lo guardamos
Set NuevoLibro = Workbooks.Add
With NuevoLibro
.SaveAs Filename:=NuevaRuta & NombreLibro, FileFormat:=52
End With
'*****************************
'valores para FileFormat
'.xlsx = 51 '(52 for Mac)
'.xlsm = 52 '(53 for Mac)
'.xlsb = 50 '(51 for Mac)
'.xls = 56 '(57 for Mac)
'*****************************
When working with large amount of data where .xlsx workbook is needed, use the following syntax
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=51
(For more FileFormats see documentation.)
I think your issue was that when you use Now(), the output will be "6/20/2014"... This an issue for a file name as it has "/" in it. As you may know, you cannot use certain symbols in a file name.

Save Workbook in current directory with title from cell

I download files where I need to rename them based on the name contained in cell A1. The file is already saved in the current directory, so what I am after is only to save to the current directory with the filename in call A1 and the extension ".xls"
Tried this code:
Sub SaveToRelativePath()
Dim relativePath As String, sname As String
sname = ActiveWorkbook.Worksheets(1).Range("A1") & ".xls"
relativePath = Application.ActiveWorkbook.Path & "\" & sname
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
But the debugger reports an error on the last line: ActiveWorkbook.SaveAs Filename:=relativePath
Any clues to how this could be done?
The error is not specified, but in case you see:
It means you try to save a workbook with the above code as "XLS" (actually, not exactly, see below) - and that means a macro-free format. Excel warns you you'll lose the code.
One more issue - regardless of extension you code will save the book as default format for the Excel version you use (and that is XLSX or xlOpenXMLWorkbook for 2007 and perhaps future versions, I have 2007). As a result, you'll get on the saved file opening something like that:
Solutions:
To avoid the 1st warning - save your initial workbook (i.e. that one where you keep the VBA code) as Macro-Enabled before running the macro.
Add proper format description to Save method - in your case that will be FileFormat:=xlExcel8 - thus you'll get true XLS.
One more thing - to avoid aby compatibility alerts when saving file as XLS, add the .CheckCompatibility = False before saving. resulting code should be smth like that:
Sub SaveToRelativePath()
Dim relativePath As String, sname As String
sname = ActiveWorkbook.Worksheets(1).Range("A1") & ".xls"
relativePath = Application.ActiveWorkbook.Path & "\" & sname
Application.DisplayAlerts = False
ActiveWorkbook.CheckCompatibility = False
ActiveWorkbook.SaveAs Filename:=relativePath, FileFormat:=xlExcel8
Application.DisplayAlerts = True
End Sub
However be careful - such construction will silently overwrite any existing file. Hope that was somehow helpful.

Simple VBA/Macro need to create a new text file with the contents of active sheet without changing filename

I need to export data in a sheet to a text file without changing the file name (i.e. not doing "save as". Also it would be great if the file name could look at the previous like file name in the folder and increase by 1 digit (i.e. :file_1.txt, file_2.txt, etc.)...
Thanks!!
If you want to avoid the current name of your excel file being changed, just save the current worksheet, not the whole workbook (the VBA equivalent of the SaveAs function is ActiveWorkbook.SaveAS, to save just the current sheet use ActiveSheet.SaveAS).
You can use the following macro:
Sub Macro1()
Application.DisplayAlerts = False
ActiveSheet.SaveAs Filename:="NewFile.txt", FileFormat:=xlTextWindows
Application.DisplayAlerts = True
End Sub
Toggling the DisplayAlerts property avoids a message box that is displayed if the given file already exists.
If want to save more than one sheet, you need to iterate through the Sheets collection of the ActiveWorkbook object and save each sheet to a separate file.
You can get a new file name as illustrated below, it includes a date. If you would like to add some details on what you want to export, you may get a fuller answer.
Function NewFileName(ExportPath)
Dim fs As Object '' or As FileSytemObject if a reference to
'' Windows Script Host is added, in which case
'' the late binding can be removed.
Dim a As Boolean
Dim i As Integer
Dim NewFileTemp As string
Set fs = CreateObject("Scripting.FileSystemObject")
NewFileTemp = "CSV" & Format(Date(),"yyyymmdd") & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = 1
Do While a
NewFileTemp = "CSV" & Format(Date(),"yyyymmdd") & "_" & i & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = i + 1
If i > 9 Then
'' Nine seems enough times per day to be
'' exporting a table
NewFileTemp = ""
MsgBox "Too many attempts"
Exit Do
End If
Loop
NewFileName = NewFileTemp
End Function

Resources