我经常发现,对于数据透视表,我最终会通过数据透视表钻取创建新工作表中的大量工作表。我认为一个很棒的宏将是在从数据透视表创建的所有新工作表的右上角显示一个小用户窗体,允许用户轻松删除工作表并返回数据透视表。但是,我无法弄清楚如何触发宏。有任何想法吗?基本上,只要在数据透视表中向下钻取创建新工作表,就需要自动触发宏。
答案 0 :(得分:0)
由于过于复杂,你可能正在寻找类似的东西......
Under" ThisWorkbook"添加以下代码:
EDITED
这对我有用:
Private Sub Workbook_NewSheet(ByVal Sh As Object)
If Detect_Pivot(Sh) Then
Sh.Activate
frmSheetOptions.Show
End If
End Sub
Function Detect_Pivot(wsNew As Worksheet) As Boolean
Dim wb As Workbook
Dim pvt As PivotTable
Dim bNew As Boolean
Dim i As Integer
i = 0
bNew = True
Set wb = ThisWorkbook
For Each pvt In wsNew.PivotTables
i = i + 1
s = Split(pvt.SourceData, "!")
sName = s(0)
If wsNew.Name = sName Then
bNew = False
Exit For
End If
Next
If i > 0 Then Detect_Pivot = bNew
End Function
你要显示的frm里面:
Private Sub cmdHide_Click()
frmSheetOptions.Hide
End Sub
Private Sub cmdDelete_Click()
ActiveSheet.Delete
frmSheetOptions.Hide
End Sub
Private Sub UserForm_Initialize()
frmSheetOptions.lblSheetName = ActiveSheet.Name
End Sub
答案 1 :(得分:0)
要在创建新工作表时启动事件,您可以使用以下示例(Tim Williams的答案)。但是,我不知道如何判断新工作表是否是从数据透视表创建的。向下钻取可能是由数据透视表触发的事件,在这种情况下,您可以应用此方法来查找它。这需要一些调查。
Private WithEvents app As Excel.Application
Sub Init()
Set app = Application 'start capturing events
End Sub
Private Sub app_NewWorkbook(ByVal Wb As Workbook)
Debug.Print "New"
End Sub
Private Sub app_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
Debug.Print "Before close: " & Wb.Name
End Sub
Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
Debug.Print "Open: " & Wb.Name
End Sub