宏按钮仅在第二次单击时起作用

时间:2019-04-24 15:37:15

标签: excel vba pivot

所以我创建了一个数据透视表和按钮。每个按钮代表一个字段,该字段将进入数据透视表的值部分。 这些字段分别是2016、2017、2018和2019年。我还创建了一个按钮来一次代表所有年份。 我还将切片器应用于其他字段和过滤器。 -对于过滤器,我只需要复制数据透视表,然后将所选字段放在数据透视表的过滤器标签中即可。 (希望如此)

我想知道为什么当我第一次启动Excel时。所有按钮均无效。仅当我第二次单击“全年”按钮时才有效,这意味着它第一次说没有找到该对象。但是我第二次单击它时,它会像平常一样工作。所有其他按钮也可以使用。

添加切片器的过滤器后,就会出现此问题。

Sub Add_Value_MasterCode()

Dim pt As PivotTable
Dim pf As PivotField
Dim SField As String

'Set Variable
 Set pt = ActiveSheet.PivotTables(1)
 SField = ActiveSheet.Shapes(Application.Caller).TextFrame.Characters.Text


'Remove Existing Fields
For Each pf In pt.DataFields
If pf.Name <> "Values" Then
    pf.Orientation = xlHidden
End If
Next pf

'Add fields that button was clicked for
pt.PivotFields(SField).Orientation = xlDataField

'Set title and color for each fields
ActiveSheet.ChartObjects("Chart 1").Chart.ChartTitle.Text = SField & " Revenue"
ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of " & SField).Caption = "Year " & SField
If SField = "2016" Then
    Call year2016
ElseIf SField = "2017" Then
    Call year2017
ElseIf SField = "2018" Then
    Call year2018
ElseIf SField = "2019" Then
    Call year2019
End If

End Sub

这是其他代码。

Sub Add_All()


Dim pt As PivotTable
Dim pf As PivotField
Dim SField As String

'Set Variable
Set pt = ActiveSheet.PivotTables(1)
SField = ActiveSheet.Shapes(Application.Caller).TextFrame.Characters.Text

'Remove Existing Fields
For Each pf In pt.DataFields
If pf.Name <> "Values" Then
    pf.Orientation = xlHidden
End If
Next pf

With ActiveSheet.PivotTables("pivottable1")
            .AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("2016"), "Year 2016", xlSum
            .AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("2017"), "Year 2017", xlSum
            .AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("2018"), "Year 2018", xlSum
            .AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("2019"), "Year 2019", xlSum
End With


ActiveSheet.ChartObjects("Chart 1").Chart.ChartTitle.Text = "All Years Revenue"

End Sub

好像不读代码

 For Each pf In pt.DataFields
 If pf.Name <> "Values" Then
   pf.Orientation = xlHidden
 End If
 Next pf

直到我第二次单击“全年”。

0 个答案:

没有答案