我正在 Excel 中构建一个工作数据透视表。有没有一种方法可以让我构建一个日历切片器,让其他人可以单击(例如)9 月 30 日,并更新数据透视表?
我的专栏是:
免责声明:我不是在寻找切片机。这些对用户不友好,因为我有 2 个日期列开始日期和结束日期
我尝试过切片机,但这些还不够好。例如,如果我的产品仅在 8 月 1 天销售,它将显示为整个月。
尝试使用 Excel 的 ActiveX 控件和一些 VBA 代码。以下是创建日历控件的解决方案,该控件根据所选日期更新数据透视表:
Developer
选项卡。如果您没有看到“开发人员”选项卡,则需要先启用它。Insert
。More Controls
(工具图标)。Microsoft Date and Time Picker Control
并单击 OK
。Properties
。将 Name
属性更改为 DatePicker
之类的内容。View Code
。Private Sub DatePicker_Change()
Dim pt As PivotTable
Dim startDateField As PivotField
Dim endDateField As PivotField
Dim selectedDate As Date
' Set the pivot table
Set pt = ThisWorkbook.Worksheets("YourPivotSheetName").PivotTables("YourPivotTableName")
' Set the start and end date fields
Set startDateField = pt.PivotFields("Start date")
Set endDateField = pt.PivotFields("End date")
' Get the selected date from the calendar control
selectedDate = Me.DatePicker.Value
' Clear any existing date filters
startDateField.ClearAllFilters
endDateField.ClearAllFilters
' Apply the date filter
startDateField.PivotFilters.Add Type:=xlDateAfter, Value1:=selectedDate - 1
endDateField.PivotFilters.Add Type:=xlDateBefore, Value2:=selectedDate + 1
End Sub
将
YourPivotSheetName
替换为包含数据透视表的工作表的实际名称,并将 YourPivotTableName
替换为数据透视表的名称。
此解决方案允许用户从日历控件中选择日期,数据透视表将更新以仅显示该日期可用的产品。