Changing a workbooks "FullName" property in the "Workbook_BeforeSave" event
I need to rename a workbook to the name of a cell when the user clicks "Save" or "Save as". My guess is that I would need to do this in the Workbook_BeforeSave
event. I have the following questions:
- How do you set the
ActiveWorkbook.FullName
property with out callingSave
,SaveAs
, orSaveCopyAs
? - Is what I am trying to do even possible without disabling the toolbar and adding custom save buttons?
I use the following code to get create the filename
Dim fName As String, sName As String
fName = Thi开发者_运维技巧sWorkbook.FullName
sName = ThisWorkbook.Name
fName = Left(fName, (Len(fName) - Len(sName))) & _
Thisworkbook.Worksheet("Cust").Range("FILE").Value & ".xls"
Thanks
You can't change the Name or Fullname properties except through a save operation. The Before_Save event has a Cancel argument that if you set to True will stop the save operation and let you do it yourself. Here's an example.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim sOldName As String
'If SaveAsUI Then
Cancel = True 'cancel the save and do it yourself in code
sOldName = Me.FullName 'store the old name so you can delete it later
'Save using the value in the cell
Application.EnableEvents = False
Me.SaveAs Me.Path & Application.PathSeparator & _
Me.Worksheets("CUST").Range("FILE").Value & ".xls"
Application.EnableEvents = True
'If the name changed, delete the old file
If Me.FullName <> sOldName Then
On Error Resume Next
Kill sOldName
On Error GoTo 0
End If
'End If
End Sub
精彩评论