![](/img/trans.png)
[英]Trying to use VBA to filter my Pivot Table based on Year and Period values in cells D2 and E2
[英]Use VBA to make pivot table sum values based on dates only?
我有一张有 2 张纸的 excel。 在工作表 1 上,我们有一个数据透视表 1,它显示了每个“帐户”和每个帐户中所有交易的总和。 在工作表 2 中,我在数据透视表 1 中引用了带有列(日期、帐户、值)的数据。 我想创建一个脚本,其中给定用户的输入日期,该脚本将运行并使数据透视表 1 对给定日期的值求和。
这可以在 vba 之外做吗? 如果不是,我应该搜索什么来开始这样的项目?
在这种情况下,恐怕唯一的方法是 VBA,因为数据透视表过滤器不允许您选择单元格。
当您开始使用 VBA 时,录制宏通常是开始的方式。 在您的情况下,您可以记录更改数据透视表中的过滤器并将过滤器调整为您需要的日期输入:
这里的问题是,当您在过滤器中输入日期时,VBA 会添加一些空字符串,因此我不得不巧妙地将它们取出。
下面的代码以一个输入框开始,要求用户输入一个日期。 然后这个日期将被更改为一个很好的字符串,供 VBA 在过滤器中使用。
Sub Macro2()
Dim a As Date
Dim Dayd, Monthd, Yeard As String
' a = Range("A1").Value You can use this instead of the input box below
a = InputBox("Date here")
' Day The lines below find the date in the format "01" - "31"
If Left(Mid(Str(Day(a)), 2, 2), 1) <> 1 And Left(Mid(Str(Day(a)), 2, 2), 1) <> 2 And Left(Mid(Str(Day(a)), 2, 2), 1) <> 3 Then
Dayd = "0" & Right(Str(Day(a)), 1)
Else
Dayd = Right(Str(Day(a)), 2)
End If
' Month These lines find the months in the same way
If Left(Mid(Str(Month(a)), 2, 2), 1) <> 1 Then
Monthd = "0" & Right(Str(Month(a)), 1)
Else
Monthd = Right(Str(Month(a)), 2)
End If
' Year
Yeard = Right(Str(Year(a)), 4)
'This is testing if the date is in the format I want ex:"15.08.2018" (dd.mm.yyy)
MsgBox (Dayd & "." & Monthd & "." & Yeard)
'Below the code from the "Record Macro"
ActiveSheet.PivotTables("PivotTable2").PivotFields("SODATE").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("SODATE").PivotFilters.Add2 _
Type:=xlCaptionIsLessThan, Value1:=Dayd & "." & Monthd & "." & Yeard
End Sub
我尝试添加注释,如果您需要更多解释,请说
@皮埃尔44
感谢您的帮助,这让我开始在一些 googlefu 之后查看数据透视过滤器字段,我能够想出这段代码来满足我的需求。
' loops through pivot table accounts and sets off the filters that are less than current date
Dim todaysdate As Date
todaysdate = Range("B2").value
Dim pff As PivotField
Dim pii As PivotItem
Set pff = ActiveSheet.PivotTables("Accounts_Pivot_Table").PivotFields("Date")
pff.ClearAllFilters
For Each pii In pff.PivotItems
If IsDate(pii) Then
If pii > todaysdate Then
pii.Visible = False
End If
End If
Next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.