Rename Worksheet Event in Excel

后端 未结 5 417
既然无缘
既然无缘 2020-12-09 12:15

What is the best way to get some VBA code to run when a excel sheet is renamed?

5条回答
  •  感动是毒
    2020-12-09 12:23

    I know this is an old question but I've recently begun to use Excel's CELL("filename") function which returns details about both file and sheet names.

    We can parse the sheet name, using this well-known formula:

    =MID(CELL(""filename"", A1),FIND(""]"",CELL(""filename""," A1))+1,255)"

    By writing this function to a hidden worksheet, and then monitoring the _Calculate event on that sheet, we can catch any change to the worksheet name.

    I had to resort to this method because I needed to share some VBA code with a client, which gave him the possibility to change certain worksheet names programmatically as well as by typing onto the tab. This method captures a sheet name changed event even if it was made in code.

    In the skeleton code below, I've just captured the name change for the active worksheet but there's nothing to stop you adding a target worksheet list and adjusting the handling code accordingly.

    The code below is in the Workbook code-behind:

    Option Explicit
    Private mSheetNamesWS As Worksheet
    Private mOldSheetName As String
    
    Private Sub Workbook_Open()
    
        'Find or create the hidden worksheet
        'containing the sheet reference.
        On Error Resume Next
        Set mSheetNamesWS = Me.Worksheets("SheetNames")
        On Error GoTo 0
    
        If mSheetNamesWS Is Nothing Then
    
            'Disable events so that the _calculate event
            'isn't thrown.
            Application.EnableEvents = False
    
            Set mSheetNamesWS = Me.Worksheets.Add
            With mSheetNamesWS
                .Name = "SheetNames"
                .Visible = xlSheetVeryHidden
            End With
    
            Application.EnableEvents = True
    
        End If
    
        'Update the sheet reference.
        If TypeOf ActiveSheet Is Worksheet Then
            UpdateCellFormula
        End If
    
    End Sub
    
    Private Sub Workbook_SheetActivate(ByVal Sh As Object)
        'Active sheet has changed so update the reference.
        If TypeOf ActiveSheet Is Worksheet Then
            UpdateCellFormula
        End If
    End Sub
    
    Private Sub UpdateCellFormula()
        Dim cellRef As String
    
        'Sense check.
        If mSheetNamesWS Is Nothing Then Exit Sub
    
        'The CELL function returns details about
        'the file and sheet name of any
        'specified range.
        'By adding a formula that extracts the
        'sheet name portion from the CELL function,
        'we can listen for any changes
        'of that value in the _calculate event method.
    
        'Disable events to avoid a spurious
        '_calculate event.
        Application.EnableEvents = False
        cellRef = ActiveSheet.Name & "!A1"
        With mSheetNamesWS.Range("A1")
            .Formula = _
                "=MID(CELL(""filename""," & _
                cellRef & _
                "),FIND(""]"",CELL(""filename""," & _
                cellRef & _
                "))+1,255)"
            mOldSheetName = .Value
        End With
        Application.EnableEvents = True
    
    End Sub
    
    Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    
        'Disregard any sheet that isn't our reference sheet.
        If Not Sh Is mSheetNamesWS Then Exit Sub
    
        'The reference sheet has recalculated.
        'It means the value of the cell containing
        'the current sheet name has changed.
        'Ergo we have a sheet name change.
    
        'Handle the event here ...
        MsgBox "You can't change the name of this sheet!"
        Application.EnableEvents = False
        ActiveSheet.Name = mOldSheetName
        Application.EnableEvents = True
    
    End Sub
    

提交回复
热议问题