Automatically name a file based on cell data when saving a spreadsheet? - excel

I have an .xltm template spreadsheet that I'm wondering if I can get a macro to populate the "save as" file name based on cell data, is this possible?
There are over 50 people who will have this spreadsheet, it's more of a form, and we are trying to figure out a way to keep the filenames uniform. I know there is the ThisWorkbook.BeforeSave, but I'm not really having any luck there. I just need it to make a file named something like $A$1 R $B$1 T $B$3.xlsx
Any ideas on how to do this?

Sure.
Sub SaveMyWorkbook()
Dim strPath As String
Dim strFolderPath as String
strFolderPath = "C:\"
strPath = strFolderPath & _
Sheet1.Range("A1").Value & "R" & _
Sheet1.Range("B1").Value & "T" & _
Sheet1.Range("B3").Value & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strPath
End Sub
EDIT: After you clarified your question in your comment below, I can now safely say that the answer is: No, what you are asking is not possible.
What is possible is to put a big, fat command button on your sheet that says "Press me to save", and have that button call the above Sub. You can set a fixed folder, as in the example above, or have the user pick a folder using the FileDialog object (or the GetSaveAsFilename function, but then the user will be able to change the suggested filename, so less safe).

Related

Excel VBA won't save: creating 8-digit alphanumeric "filename"

I am new to VBA. I am using a "shell" macro to run another macro on a series of files. It won't save. I am going to include my code here and also a series of photos because the photos were the only way to show the result of hovering over the values in the code.
So, the error message is generating something I don't understand. But it is clear that the links in the code link to what the results should be, so I'm confused.
This is the code:
Sub SHELLforMacros()
Dim wbMatrix As Workbook
Dim strFileName As String
Dim strFileName As String
Dim newFileName As String
Dim strPath As String
Dim strExt As String
Dim objWorkbook As Workbook
Dim ws As Worksheet
Dim Sheetname As Worksheet
Set Sheetname = Worksheets(1)
Dim Worksheet As Worksheet
Dim rng As Range
Set rng = Range("A2")
strPath = "C:\Users\myname\Desktop\All_mricgcm3_files\45\Fall45\test\"
strExt = "csv"
strFileName = Dir(strPath & "*." & strExt)
While strFileName <> ""
Set wbMatrix = Workbooks.Open(strPath & strFileName)
Application.Run "'C:\Users\myname\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB'!Graph_NEW"
strPath = "C:\Users\myname\All_mricgcm3_files\45\Fall45\test\"
newFileName = Sheetname.Range("A2").Value
ActiveWorkbook.SaveAs fileName:=strPath & newFileName, FileFormat:=51
ActiveWorkbook.Close SaveChanges:=True
Wend
End Sub
What this macro is supposed to do is open a file, run another macro on the file (creating a graph), and then save the file with the same name but as an .xlsx file. Then open the next file in the folder and do the same, until it runs out of files. I realize the code may not be the most current. It is cobbled together from things I've found online. Thanks for any help.
Edit: UPDATE - I removed all the section on saving and closing the file from the "shell" macro and put it into the "Graph_NEW" macro. Now the "shell" macro is running fine. But I am running into the same issue with the "Graph_NEW" macro now. It is exactly the same error message as highlighted in the first image, only each time there is a new 8-digit alphanumeric "filename" that it is looking for. This seems like a very specific thing.
I changed the section in the following ways, successively, in an attempt to debug. I added With and End With around the section:
With WB
ActiveWorkbook.Save
newFileName = Sheetname.Range("A2").Value
strPath = "C:\Users\qmontana\All_mricgcm3_files\mric45\Fall45\test\"
ActiveWorkbook.SaveAs fileName:=strPath & newFileName & ".xlsx", FileFormat:=51
ActiveWorkbook.Close SaveChanges:=True
End With
I changed the name of the folder from "45" to "mric45" thinking that maybe it didn't like a number as a folder name.
I removed the "backslash" at the end of the strPath--and then the 8-digit alphanumeric string showed up as an error after the Fall45 folder, like this "C:\Users\myname\Desktop\All_mricgcm3_files\45\Fall45\777GTY78". Yet, as I've shown in the images, all indications are that it knows what file it is working with. There are no "blank spaces" in the pathname.
I tried taking the underscores out of the folder "All_mricgcm3_files".
I moved the line newFileName = Sheetname.Range("A2").Value to come before the strPath line.
Where is this 8-digit alphanumeric "filename" coming from?? (See error code, first image.)
Ok, it was a very simple thing, in case anyone else runs into this problem.
Took me two days to find out though --> I had somehow dropped a folder layer in the path name. The catch? The alphanumeric string was showing up at the end of the path name, not where the folder layer was missing. That's why I was thrown off because my focus was on the ending.
When I added that folder\ back in, I had no more problem with saving and the macro ran fine.

How can I change an image in Excel using a macro that reads a cell and matches it with the image file name?

My idea is to write a macro which is assigned to a button that does the same thing as right-clicking the image and using "Change picture..." and then uses information in a cell to find the correct picture (Lastname, firstname.jpg). Having never worked with excel macros before, you can imagine my dilemma.
Lets say all the pictures are stored under this file path: C:\MyLocalData\hendrik.voelker\Pictures\Portraits
and all use this naming convention:
LASTNAME, FIRSTNAME.JPG
If someone could help me out with this issue that would be amazing! Thanks in advance.
UPDATE: I now have the following code for an ActiveX Control image:
Sub New_Pic()
Dim strPath As String, strFile As String
strPath = "C:\MyLocalData\john.smith\Pictures\Portraits\"
strFile = Range("M15").Value & ".jpg"
If Len(Dir(strPath & strFile)) Then
ActiveSheet.Image1.PictureSizeMode = fmPictureSizeModeZoom
ActiveSheet.Image1.Picture = LoadPicture(strPath & strFile)
Else
MsgBox strFile, vbExclamation, "Image Not Found"
End If
End Sub
But the picture inserts in a landscape rather than the desired portrait orientation. I would also like a black border. Any ideas on these two issues?

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.

Reusability for a VLOOKUP macro

I am trying to create a macro which includes a VLOOKUP but the VLOOKUP file would change each time. I would like the reference file in the VLOOKUP to be a variable. Ideally the macro would prompt the user to choose a file they wish to VLOOKUP from. So far I have this but it doesn't seem to be working...("test" is what the worksheet is named).
Sub VLOOKUP()
Application.ScreenUpdating = False
Dim myFilename As String
MsgBox "Please choose file with name to use in VLOOKUP formula.", vbOKOnly, "Choose file"
myFilename = CStr(Application.GetOpenFilename)
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'[" & myFilename & "]test'!C9:C10,2,0)"
End Sub
However, the VLOOKUP in the cell is not showing up how it should. e.g.
=VLOOKUP(B12,'[G:\OPS\National Pricing Data And Risk\Vehicle Pricing\VP Work\Gareth\Even Newer Toyota Macro Test\[Z401 Toyota Test COMPLETE.xlsx]test]Z401 Toyota Test COMPLETE.xlsx]'!$I:$J,2,0)
I'm not sure where the extra ]Z401 Toyota Test COMPLETE.xlsx] is coming from. Is there something I'm missing/not doing correctly?
Edit:
Sub VLOOKUP()
Application.ScreenUpdating = False
Dim fullPath As String
Dim tmpName As String
Dim tmpPath As String
Dim myFilename As String
fullPath = "G:\OPS\National Pricing Data And Risk\Calculators, Docs, Templates & Guides\Toyota Macros.xlsm"
tmpName = fso.GetFileName(fullPath)
tmpPath = fso.GetParentFolderName(fullPath)
myFilename = tmpPath & "\[" & tmpName & "]"
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'[" & myFilename & "]test'!C9:C10,2,0)"
End Sub
Isn't VLOOKUP a "reserved word" in Excel? Your function may not be working because you're trying to use an Excel function that already exists. Maybe try calling your function "MYVLOOKUP" and see if that works.
Brian
Excel doesn't like the way you've formatted your filename. You need to split it into directory and name.ext so you can format it like this:
'c:\path\to\file\[filename.ext]worksheetName'!F1
Edit
I forgot that this isn't as straightforward in VBA as it is in other languages. The easiest way is to use the FileSystemObject, but to use that you first have to reference it. You can see instructions on how to add the reference in this stackoverflow answer: https://stackoverflow.com/a/1755577/2295754.
And here's an example of how to use the FileSystemObject, in case you need a little more guidance than the other stackoverflow answer gave.
Dim fso As New FileSystemObject
fullPath = "D:\Ashby\Documents\test2.xlsx"
tmpName = fso.GetFileName(fullPath )
tmpPath = fso.GetParentFolderName(fullPath )
myFilename = tmpPath & "\[" & tmpName & "]"
Edit2
So, I intentionally left out the actual use of myFilename last time hoping you'd pick that up on your own. Oh well, here it is:
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'" & myFilename & "test'!C9:C10,2,0)"

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.

Resources