拦截工作簿保存事件并将字符串附加到工作簿文件名的末尾

时间:2015-10-21 21:26:14

标签: excel-vba vba excel

我知道如何在模块级别拦截工作簿的保存事件:

Dim WithEvents app As Application

Private Sub app_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean)


End Sub

我想要做的是在实际文件名的末尾添加一个字符串。例如,如果我使用名称Sales.xls保存,我希望能够自动将_extract添加到结尾,以便名称为Sales_extract.xls,但我无法弄清楚怎么做。

2 个答案:

答案 0 :(得分:1)

把它放在你的子

Dim myFileName As String
myFileName = ActiveWorkbook.FullName
ActiveWorkbook.SaveAs Filename:=Split(myFileName, ".")(0) & "test." & Split(myFileName, ".")(1)

更改“测试”。任何你想要的东西,但要确保它以“。”结束。

答案 1 :(得分:1)

您可以在ThisWorkbook模块中截取事件:

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    Const CUSTOM_NAME As String = "_extract"

    Dim fn As String

    fn = Me.Name
    If InStr(fn, ".") > 0 Then fn = Left(fn, InStrRev(fn, ".") - 1)

    Cancel = Not Right(fn, Len(CUSTOM_NAME)) = CUSTOM_NAME

    If Cancel Then
        Application.EnableEvents = False
        'Application.DisplayAlerts = False
        Me.SaveAs Me.Name & "_extract" & Right(Me.Name, InStrRev(Me.Name, ".") - 1)
        'Application.DisplayAlerts = True
        Application.EnableEvents = True
    End If
End Sub