使用日期范围将格式化日期填充到数组中

时间:2018-03-03 17:31:01

标签: arrays excel vba pivot-table

我正在尝试使用一些vba代码更新excel中非活动工作表上的数据透视表。我想使用日期范围动态过滤数据透视表。必须以特定格式逐日添加范围,以便数据透视表可以正确读取日期。我需要基本上采用日期范围 - >格式化 - >并将其添加到我的数据透视表可用于更新过滤器的数组中。我已经附加了下面的代码,该代码成功更新了数据透视表,其中包含一个日期但不包括范任何指导都很受欢迎,因为我对VBA很新,并且正在努力学习最佳实践。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'This line stops the worksheet updating on every change, it only updates when cell
'H6 or H7 is touched
If Intersect(Target, Range("H1")) Is Nothing Then Exit Sub

'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim arrDateFilter As Variant
Dim NewDate1 As String
Dim dateValue1 As Date
Dim NewDate2 As String
Dim dateValue2 As Date

'Here you amend to suit your data
Set pt =Worksheets("BillingPivot").PivotTables("BillingPivot_T")
Set Field = pt.PivotFields( _
    "[Billing].[Expected Book Date (no time)].[Expected Book Date (no time)]" _
    )
NewDate1 = Worksheets("BillingPivot").Range("H1").Value
dateValue1 = CDate(NewDate1)
NewDate2 = Worksheets("BillingPivot").Range("I1").Value
dateValue2 = CDate(NewDate2)

'This updates and refreshes the PIVOT table
With pt
.PivotFields("[Billing].[Expected Book Date (no time)].[Expected Book Date (no time)]").ClearAllFilters


arrDateFilter = "[Billing].[Expected Book Date (no time)].&[" & Format(NewDate1, "YYYY-MM-DD") & "T00:00:00]"

ActiveSheet.PivotTables("BillingPivot_T").PivotFields( _
    "[Billing].[Expected Book Date (no time)].[Expected Book Date (no time)]" _
    ).VisibleItemsList = Array(arrDateFilter)

'Refresh the table with new data
.RefreshTable
End With
End Sub

0 个答案:

没有答案