PDA

View Full Version : Auto generate Excel File Name?



FlakeyPuf
04-24-2008, 05:06 PM
Is there a way to get Excel to auto generate a file name based on the content of a specific cell? I found some coding for a macro, but I couldn't get it to work. I'm a complete Macro newbie, I've never used them before. Any assistance would be most appreciated!

Here's what I found. I just copied it entirely into the macro edit, hoping for the best. I'm thinking I need step by step instruction (sorry). I'm guessing Sub is the macro title? Should I not have copied the Option Explicit part?

Option Explicit

Sub SaveAsExample()

Dim FName As String
Dim FPath As String

FPath = "C:"
FName = Sheets("Sheet1").Range("A1").Text
ThisWorkbook.SaveAs Filename:=FPath & "\" & FName

End Sub

Simon Lloyd
04-24-2008, 05:29 PM
The code above is fine, yes you should have copied Option Explicit as it checks to see if you declared your variables, this is from the VBA help files: -


Used at module level to force explicit declaration of all variables in that module.

Syntax

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a module before any procedures.

When Option Explicit appears in a module, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

If you don't use the Option Explicit statement, all undeclared variables are of Variant type unless the default type is otherwise specified with a Deftype statement.

Note Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.
it may not have worked if you don't have access to the particular drive, usually you need to set the path if on a networked computer like:

Sub SaveAsExample()

Dim FName As String

FName = Sheets("Sheet1").Range("A1").Text
ThisWorkbook.SaveAs Filename:=ThisWorkbook.Path & ThisWorkbook.Name & "-" & FName

End Sub
where the workbook is saved in the same area as the original, with the original name plus the name from sheet1 A1, and if you want it automatically on closing the workbook:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.SaveAs (ThisWorkbook.Name & "-" & Range("A1").Value)
End Sub

however with the all the above the original workbook does not have the changes saved.