在“Workbook_BeforeSave”事件中更改工作簿“FullName”属性

时间:2011-02-02 18:27:59

标签: excel excel-vba vba

当用户点击“保存”或“另存为”时,我需要将工作簿重命名为单元格的名称。我的猜测是我需要在Workbook_BeforeSave事件中执行此操作。我有以下问题:

  • 如何在不调用ActiveWorkbook.FullNameSaveSaveAs的情况下设置SaveCopyAs媒体资源?
  • 在不禁用工具栏和添加自定义保存按钮的情况下,我正在尝试做什么?

我使用以下代码来创建文件名

Dim fName As String, sName As String
fName = ThisWorkbook.FullName
sName = ThisWorkbook.Name    
fName = Left(fName, (Len(fName) - Len(sName))) & _ 
         Thisworkbook.Worksheet("Cust").Range("FILE").Value & ".xls"

由于

1 个答案:

答案 0 :(得分:1)

除非通过保存操作,否则无法更改“名称”或“全名”属性。 Before_Save事件有一个Cancel参数,如果设置为True,将停止保存操作,让你自己动手。这是一个例子。

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