检测工作表的重命名或删除

时间:2015-09-21 23:02:28

标签: excel vba worksheet

有没有办法检测用户何时

  • 重命名,或
  • 删除工作表?

如果发生其中一个事件,我想运行一些代码。

我尝试了什么

我的工具使用了很多事件处理程序,所以我想到的一件事就是在每个Worksheet_Change期间循环遍历所有的工作表名称,但我不认为这是最好的方法。

1 个答案:

答案 0 :(得分:1)

此方法属于ThisWorkbook模块。

Public shArray1 As Variant
Public shArray2 As Variant

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Dim lngCnt As Long
Dim strMsg As String
Dim strSht
Dim vErr
Dim strOut As String

'get all sheet names efficiently in a 1D array
ActiveWorkbook.Names.Add "shtNames", "=RIGHT(GET.WORKBOOK(1),LEN(GET.WORKBOOK(1))-FIND(""]"",GET.WORKBOOK(1)))"
shArray2 = Application.Transpose([INDEX(shtNames,)])
strSht = Application.Transpose(Application.Index(shArray2, , 1))

'exit here if first time code is run
If IsEmpty(shArray1) Then
    shArray1 = shArray2
    Exit Sub
End If

`check each sheet name still exists as is  
For lngCnt = 1 To UBound(shArray1)
   vErr = Application.Match(shArray1(lngCnt, 1), strSht, 0)
   If IsError(vErr) Then
        strOut = strOut & shArray1(lngCnt, 1) & vbNewLine
        vErr = Empty
  End If
Next

shArray1 = Application.Transpose([INDEX(shtNames,)])

If Len(strOut) > 0 Then MsgBox strOut, vbCritical, "These sheets are gone or renamed"

End Sub