Make the VBA handle pivot fields in the filters section.

Tread the PivotTable filters the same as the row headers, making them
part of the WHERE clause in the SQL statement.
This commit is contained in:
PhilRunninger 2024-03-19 16:21:18 -04:00
parent 4c1584af3d
commit aa13911c02
7 changed files with 40 additions and 6 deletions

Binary file not shown.

View File

@ -38,6 +38,30 @@ Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean
Dim pf As PivotField
Dim pi As PivotItem
' Serialize the report filters in SQL and JSON format.
pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
pt.PivotCache.Refresh
Dim segmSql As String
Dim segmJSql As String
segmSql = "segm IN ("
segmJSql = """segm"": ["
Set pf = pt.PivotFields("segm")
For Each pi In pf.PivotItems
If pi.Visible Then
If Right(segmSql, 1) <> "(" Then
segmSql = segmSql & ", "
segmJSql = segmJSql & ", "
End If
segmSql = segmSql & "'" & escape_sql(pi.Name) & "'"
segmJSql = segmJSql & """" & escape_json(pi.Name) & """"
End If
Next
segmSql = segmSql & ")"
segmJSql = segmJSql & "]"
' Serialize the row items in SQL and JSON format.
Set ri = Target.Cells.PivotCell.RowItems
Set ci = Target.Cells.PivotCell.ColumnItems
Set df = Target.Cells.PivotCell.DataField
@ -45,18 +69,28 @@ Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean
Set rd = Target.Cells.PivotTable.RowFields
Set cd = Target.Cells.PivotTable.ColumnFields
ReDim handler.sc(ri.Count, 1)
Dim segmOffset As Integer
segmOffset = IIf(Right(segmSql, 2) = "()", 0, 1)
handler.sql = ""
handler.jsql = ""
ReDim handler.sc(ri.Count + segmOffset, 1)
If segmOffset = 1 Then
handler.sql = segmSql
handler.jsql = segmJSql
handler.sc(0, 0) = "segm"
handler.sc(0, 1) = Mid(segmJSql, 9)
End If
For i = 1 To ri.Count
If i <> 1 Then handler.sql = handler.sql & vbCrLf & "AND "
If i <> 1 Then handler.jsql = handler.jsql & vbCrLf & ","
If handler.sql <> "" Then handler.sql = handler.sql & vbCrLf & "AND "
If handler.sql <> "" Then handler.jsql = handler.jsql & vbCrLf & ","
handler.sql = handler.sql & rd(piv_pos(rd, i)).Name & " = '" & escape_sql(ri(i).Name) & "'"
jsql = jsql & """" & rd(piv_pos(rd, i)).Name & """:""" & escape_json(ri(i).Name) & """"
handler.sc(i - 1, 0) = rd(piv_pos(rd, i)).Name
handler.sc(i - 1, 1) = ri(i).Name
handler.jsql = handler.jsql & """" & rd(piv_pos(rd, i)).Name & """:""" & escape_json(ri(i).Name) & """"
handler.sc(i - 1 + segmOffset, 0) = rd(piv_pos(rd, i)).Name
handler.sc(i - 1 + segmOffset, 1) = ri(i).Name
Next i
scenario = "{" & handler.jsql & "}"