VBA* Loop 2 Slicers and Convert them to PDF/Excel in Custom Folder

Armygeddan

Board Regular
Joined
Apr 6, 2016
Messages
79
Final product :

1. Loop both Slicers (Slicer_Region, Slicer_Customer)
2. Save each Slicer loop as a PDF and Excel file
3. Only save certain Tabs in the whole file when exporting to PDF and Excel (Array)
4. Have the File Save Format as YYYY_MM(Previous Month)_FilePath(NamedRange).Pdf/Excel
5. Create a Year and a Month Folder in the File Save Destination if it doesn’t exist

I’ve got #3, #4, and #5 completed but need help with #1 and #2

When running the Loop and Converting the Slicer Items to PDF and Excel, it needs to save each selection in a certain name save format of YYYY_MM_CELLA_CELLB

For Region, I’ve got
“Middle East/Africa” as “MEA” “Asia/Pacific” as “AP” Single names like Canada are standalone as themselves When running the Loop, Asia/Pacific would need to be converting to the format of AP(Slicer_Customer)
So per Save, it will need to look like the following
<CODE> Save 1
– CELLA_CELL1
Save 2
– CELLA_CELL2 Etc
Save 16
– CELLB_CELL1
Save 17
– CELLB_CELL2

</CODE>I’d also like an initial save of both the Slicer Dashboards with nothing selected on the Slicers and name it as “ALL_ALL”
That’s a lot of loops to save but sure beats doing it manually.
Here is how my Slicer looks like (Edited out confidential information)

2r3i07c.jpg


I’ve only been working with VBA for a couple of months so all of the above is quite a bit advanced for me but would give me a huge learning curve for future projects like this. I’ve got the Basics of VBA down but working with Slicers has thrown me in for a Loop (Pun Intended)

Please note that all my data was initially pulled with OLAP but it is all saved in a PowerPivot Data Model so there should be no worries of external sources when gathering data from external sources when the Slicers are selected.

Thank you so much in advance, I know this is asking a lot.
Here is what I have so far:

(Please Note I am current getting an error on Line 20) Says “For Each Slice In MySlicer.SlicerItem” And the error says “Run-time error '1004' Application-defined or object-defined error”

Code:
Sub LoopSlicer()
Dim strGenericFilePath     As String: strGenericFilePath = Range("FilePath")
Dim strYearSlash           As String: strYearSlash = Year(Date) & "\"
Dim strMonthSlash          As String: strMonthSlash = CStr(Format(DateAdd("M", -1, Date), "MM")) & "\"
Dim strYearBracket         As String: strYearBracket = Year(Date) & "_"
Dim strMonthBracket        As String: strMonthBracket = CStr(Format(DateAdd("M", -1, Date), "MM")) & "_" & "Smart_Data_"
Dim strFileName            As String: strFileName = "Standard_Customer"
Dim IntSliceCount          As Integer
Dim IntLoop                As Integer
Dim SliceLoop              As Integer
Dim Slice                  As SlicerItem
Dim MySlicer               As SlicerCache
Set MySlicer = ActiveWorkbook.SlicerCaches("Slicer_Region")
    IntSliceCount = 0
    ' Count slicer options
    For Each Slice In MySlicer.SlicerItem
        IntSliceCount = IntSliceCount + 1
    Next Slice
    ' NOTE:--------------------------------------------------------------------------
    ' When selecting a slicer, all the other slicers in the field must be de-selected
    ' -------------------------------------------------------------------------------
    ' Activate slicers one by one and print
    With MySlicer
        For IntLoop = 1 To IntSliceCount
        ' Activate the current slicer in loop, deactivate rest
            For SliceLoop = 1 To IntSliceCount
                If IntLoop = SliceLoop Then
                    .SlicerItems(IntLoop).Selected = True
                Else
                    .SlicerItems(SliceLoop).Selected = False
                End If
            Next SliceLoop
        Application.DisplayAlerts = False
        ' Check for the Year Folder and create it if it does not exist
        If Len(Dir(strGenericFilePath & strYearSlash, vbDirectory)) = 0 Then
            MkDir strGenericFilePath & strYearSlash
        End If
        
        ' Check for the Month Folder and create it if it does not exist
        If Len(Dir(strGenericFilePath & strYearSlash & strMonthSlash, vbDirectory)) = 0 Then
            MkDir strGenericFilePath & strYearSlash & strMonthSlash
        End If
        On Error Resume Next
        On Error GoTo 0
        
        ' Converts to PDF and saves with YYYY_MM_ Format + Filename based off of FilePath String
        ThisWorkbook.Sheets(Array("TestSheet1", "TestSheet2", "TestSheet3")).Select
        ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:= _
        strGenericFilePath & strYearSlash & strMonthSlash & strYearBracket & strMonthBracket & strFileName, _
        Quality:=QualityStandard, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
        Application.DisplayAlerts = True
        ' Popup Message that the conversion and save is complete as YYYY_MM_Standard_Customer
        MsgBox "File Saved As:" & vbNewLine & "\" & strYearBracket & strMonthBracket & strFileName
        ' De-activate the current slicer in loop, activate the rest
        For SliceLoop = 1 To IntSliceCount
            If IntLoop = SliceLoop Then
                .SlicerItems(IntLoop).Selected = False
            Else
                .SlicerItems(SliceLoop).Selected = True
            End If
        Next SliceLoop
    Next IntLoop
End With
End Sub
 
1. I changed the name in each of the Slicer Settings settings to "Customer_1" and "Region_1" from the same names without the underscores and am running into a Run-time error '5': Invalid procedure call or arguement

2. After the running the Snippit you just gave me, it did nothing in the Test_Folder. Nothing in the whole code so far has done anything regarding the Test_Folder. I'll post entire code of what I currently have below

3. When running that Snippit, it did give me 25 dialogue boxes which each said

"Chart_down_mo", "Chart_Down_day", "Chart_PL_M", "Chart_PL_YTD", "Chart_Out_mo", "Chart_Out_day", "Chart 11", "Chart 12", "Chart 14", "Chart 15", "Textbox 4", "TextBox 35", "TextBox 36", "TextBox 38", "TextBox 39", "TextBox 9", "TextBox 40", "TextBox 13", "TextBox 45", "Picture 42", "Chart_Type", "Customer_1", "Region_1", "TextBox1", "TextBox2"

which each dialogue box at the top of each pop up counting up from "Shape 1", "Shape 2", etc

Here is what I currently have as my whole code

Code:
Option Explicit
Sub LoopSlicerTest()
Dim GenFilePath$: GenFilePath = Range("FilePath")
Dim ySlash$: ySlash = Year(Date) & "\"
Dim strMonthSlash$: strMonthSlash = CStr(Format(DateAdd("M", -1, Date), "MM")) & "\"
Dim strYearBracket$: strYearBracket = Year(Date) & "_"
Dim strMonthBracket$: strMonthBracket = CStr(Format(DateAdd("M", -1, Date), "MM")) & "_" & "Smart_Data_"
Dim fname$, Slicer1Count%, slicer2count%, IntLoop%, j%, k%
Dim SliceLoop%, Slice As SlicerItem, myslicer1 As SlicerCache, myslicer2 As SlicerCache
Set myslicer1 = ActiveWorkbook.SlicerCaches("Slicer_Region_1")
Set myslicer2 = ActiveWorkbook.SlicerCaches("Slicer_Customer_1")
Slicer1Count = myslicer1.SlicerItems.Count
slicer2count = myslicer2.SlicerItems.Count
' When selecting an item, all the other items in the slicer must be de-selected
For IntLoop = 1 To Slicer1Count
    Sheets("TestSheet1").Activate              ' sheet where the slicers are
    For SliceLoop = 1 To Slicer1Count       ' Activate the current item in loop, deactivate rest
        If IntLoop = SliceLoop Then
            myslicer1.SlicerItems(IntLoop).Selected = True
        Else
            myslicer1.SlicerItems(SliceLoop).Selected = False
        End If
    Next SliceLoop
    Application.DisplayAlerts = False
    ' Check for the Year Folder and create it if it does not exist
    If Len(Dir(GenFilePath & ySlash, vbDirectory)) = 0 Then MkDir GenFilePath & ySlash
    ' Check for the Month Folder and create it if it does not exist
    If Len(Dir(GenFilePath & ySlash & strMonthSlash, vbDirectory)) = 0 Then MkDir GenFilePath & ySlash & strMonthSlash
    For j = 1 To slicer2count
        Sheets("TestSheet1").Activate
        For k = 1 To slicer2count                           ' second slicer
            If j = k Then
                myslicer2.SlicerItems(j).Selected = True
            Else
                myslicer2.SlicerItems(k).Selected = False
            End If
        Next
        ThisWorkbook.Sheets(Array("TestSheet1", "TestSheet2", "TestSheet3")).Select
        fname = GenFilePath & ySlash & strMonthSlash & strYearBracket & strMonthBracket & _
        myslicer1.SlicerItems(IntLoop).Caption & "-" & myslicer2.SlicerItems(j).Caption
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fname, _
        Quality:=xlQualityStandard, IgnorePrintAreas:=False, OpenAfterPublish:=False
        Application.DisplayAlerts = True
        MsgBox "File Saved As:" & vbNewLine & "\" & fname
    Next
Next IntLoop
End Sub
Sub Converter()
Dim arr, i%, j%, s$, c%
arr = Array("Middle East/Africa", "Asia/Pacific", "Canada", "Zulu/Zigzag")
For i = LBound(arr) To UBound(arr)
    s = ""
    Select Case InStr(arr(i), "/")
        Case Is > 0
            For j = 1 To Len(arr(i))
                c = Asc(Mid(arr(i), j, 1))
                If c > 64 And c < 91 Then s = s & Mid(arr(i), j, 1)
            Next
            arr(i) = s
    End Select
    MsgBox arr(i)
Next
End Sub
Sub NothingSelected()
Dim ws As Worksheet
Set ws = ActiveSheet
ActiveWorkbook.SlicerCaches("Slicer_Customer").ClearManualFilter
ActiveWorkbook.SlicerCaches("Slicer_Region").ClearManualFilter
ws.ExportAsFixedFormat xlTypePDF, "C:\Users\E063699\Desktop\Test_Folder\all_all", xlQualityStandard, , 0, , , 0
End Sub
Sub ShapeNames()
Dim i%
For i = 1 To ActiveSheet.Shapes.Count
MsgBox ActiveSheet.Shapes(i).Name, 64, "Shape #" & i
Next
End Sub
 
Upvote 0

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
1. In the code, try using the name that appears at the “name to be used in formulas” line, at the slicer settings dialog box.
2. See if the code below creates the pdf file, it’s working for me.

Code:
Sub NothingSelected()
Dim ws As Worksheet, p$
Set ws = ActiveSheet
ActiveWorkbook.SlicerCaches("Volume").ClearManualFilter
ActiveWorkbook.SlicerCaches("Slicer_Region").ClearManualFilter
p = "c:\pub"                                                        ' your path here
Select Case pathexists(p)
    Case True
        ws.ExportAsFixedFormat xlTypePDF, p & "\all_all_monday", xlQualityStandard, , 0, , , 0
    Case False
        MsgBox "Path does not exist!", vbCritical
End Select
End Sub


Function pathexists(pn) As Boolean
If Dir(pn, vbDirectory) = "" Then
    pathexists = 0
Else
    pathexists = (GetAttr(pn) And vbDirectory) = vbDirectory
End If
End Function
 
Upvote 0
1. I changed "Volume" to "Slicer_Customer" because it was getting an error
2. It worked, it created a PDF of the main Dashboard with none of the Slicers selected and it's called "all_all_monday.pdf"
 
Upvote 0
Sorry, I am having a busy week.
Would the next step be adding the region conversion code to the main macro? Is something else not working?
 
Upvote 0
No worries

And I'd assume so. From my understanding, you got all the peices and even got the Conversion part working, it's just putting it all together now.
Only issue we had before was it not reading the Slicers we wanted from the main Dashboard but from a few posts ago it seemed to pick it up.
I've only been working with VBA for a couple of months so pretty much all you've done is over my head. Thanks
 
Upvote 0
Hi

Please test this new version and check if it creates the pdf files with correct names and contents, I can’t be sure with my sample data:

Code:
Function Conv$(sc$)
Dim j%, c%
Conv = ""
Select Case InStr(sc, "/")
    Case Is > 0
        For j = 1 To Len(sc)
            c = Asc(Mid(sc, j, 1))
            If c > 64 And c < 91 Then Conv = Conv & Mid(sc, j, 1)
        Next
End Select
If Len(Conv) = 0 Then Conv = sc
End Function


Sub LoopSlicer()
Dim GenFilePath$: GenFilePath = Range("FilePath")
Dim ySlash$: ySlash = Year(Date) & "\"
Dim MonthSlash$: MonthSlash = CStr(Format(DateAdd("M", -1, Date), "MM")) & "\"
Dim strYearBracket$: strYearBracket = Year(Date) & "_"
Dim strMonthBracket$: strMonthBracket = CStr(Format(DateAdd("M", -1, Date), "MM")) & "_" & "Smart_Data_"
Dim fname$, slicer1count%, slicer2count%, IntLoop%, j%, k%
Dim SliceLoop%, Slice As SlicerItem, myslicer1 As SlicerCache, myslicer2 As SlicerCache
Set myslicer1 = ActiveWorkbook.SlicerCaches("Slicer_car_status")        ' change slicers names here
Set myslicer2 = ActiveWorkbook.SlicerCaches("Slicer_area")
slicer1count = myslicer1.SlicerItems.Count
slicer2count = myslicer2.SlicerItems.Count
' When selecting an item, all the other items in the slicer must be de-selected
For IntLoop = 1 To slicer1count
    Sheets("bidding").Activate              ' sheet where the slicers are
    For SliceLoop = 1 To slicer1count       ' Activate the current item in loop, deactivate rest
        If IntLoop = SliceLoop Then
            myslicer1.SlicerItems(IntLoop).Selected = True
        Else
            myslicer1.SlicerItems(SliceLoop).Selected = False
        End If
    Next SliceLoop
    Application.DisplayAlerts = False
    ' Check for the Year Folder and create it if it does not exist
    If Len(Dir(GenFilePath & ySlash, vbDirectory)) = 0 Then MkDir GenFilePath & ySlash
    ' Check for the Month Folder and create it if it does not exist
    If Len(Dir(GenFilePath & ySlash & MonthSlash, vbDirectory)) = 0 Then MkDir GenFilePath & ySlash & MonthSlash
    For j = 1 To slicer2count
        Sheets("bidding").Activate                          ' <=== change sheet name here
        For k = 1 To slicer2count                           ' second slicer
            If j = k Then
                myslicer2.SlicerItems(j).Selected = True
            Else
                myslicer2.SlicerItems(k).Selected = False
            End If
        Next
        ThisWorkbook.Sheets(Array("TestSheet1", "TestSheet2", "TestSheet3")).Select
        fname = GenFilePath & ySlash & MonthSlash & strYearBracket & strMonthBracket & _
        Conv(myslicer1.SlicerItems(IntLoop).Caption) & "-" & Conv(myslicer2.SlicerItems(j).Caption)
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fname, _
        Quality:=xlQualityStandard, IgnorePrintAreas:=False, OpenAfterPublish:=False
        Application.DisplayAlerts = True
        MsgBox "File Saved As:" & vbNewLine & "\" & fname, 64, "slicer 1 item#" & IntLoop & " / " & "slicer 2 item#" & j
    Next
Next IntLoop
End Sub
 
Upvote 0
I am getting a Run-Time error '1004 Application-defined or object-defined error on the following line

Code:
slicer1count = myslicer1.SlicerItems.Count

Here is what I have with custom changes to my project

Code:
Function Conv$(sc$)
Dim j%, c%
Conv = ""
Select Case InStr(sc, "/")
    Case Is > 0
        For j = 1 To Len(sc)
            c = Asc(Mid(sc, j, 1))
            If c > 64 And c < 91 Then Conv = Conv & Mid(sc, j, 1)
        Next
End Select
If Len(Conv) = 0 Then Conv = sc
End Function

Sub LoopSlicer()
Dim GenFilePath$: GenFilePath = Range("FilePath")
Dim ySlash$: ySlash = Year(Date) & "\"
Dim MonthSlash$: MonthSlash = CStr(Format(DateAdd("M", -1, Date), "MM")) & "\"
Dim strYearBracket$: strYearBracket = Year(Date) & "_"
Dim strMonthBracket$: strMonthBracket = CStr(Format(DateAdd("M", -1, Date), "MM")) & "_" & "Smart_Data_"
Dim fname$, slicer1count%, slicer2count%, IntLoop%, j%, k%
Dim SliceLoop%, Slice As SlicerItem, myslicer1 As SlicerCache, myslicer2 As SlicerCache
Set myslicer1 = ActiveWorkbook.SlicerCaches("Slicer_Region")        ' Change slicers names here
Set myslicer2 = ActiveWorkbook.SlicerCaches("Slicer_Customer2")
slicer1count = myslicer1.SlicerItems.Count
slicer2count = myslicer2.SlicerItems.Count
' When selecting an item, all the other items in the slicer must be de-selected
For IntLoop = 1 To slicer1count
    Sheets("").Activate              ' Sheet where the slicers are
    For SliceLoop = 1 To slicer1count       ' Activate the current item in loop, deactivate rest
        If IntLoop = SliceLoop Then
            myslicer1.SlicerItems(IntLoop).Selected = True
        Else
            myslicer1.SlicerItems(SliceLoop).Selected = False
        End If
    Next SliceLoop
    Application.DisplayAlerts = False
    ' Check for the Year Folder and create it if it does not exist
    If Len(Dir(GenFilePath & ySlash, vbDirectory)) = 0 Then MkDir GenFilePath & ySlash
    ' Check for the Month Folder and create it if it does not exist
    If Len(Dir(GenFilePath & ySlash & MonthSlash, vbDirectory)) = 0 Then MkDir GenFilePath & ySlash & MonthSlash
    For j = 1 To slicer2count
        Sheets("TestSheet1").Activate                          ' <=== Change sheet name here
        For k = 1 To slicer2count                           ' Second slicer
            If j = k Then
                myslicer2.SlicerItems(j).Selected = True
            Else
                myslicer2.SlicerItems(k).Selected = False
            End If
        Next
        ThisWorkbook.Sheets(Array("TestSheet1", "TestSheet2", "TestSheet3")).Select
        fname = GenFilePath & ySlash & MonthSlash & strYearBracket & strMonthBracket & _
        Conv(myslicer1.SlicerItems(IntLoop).Caption) & "-" & Conv(myslicer2.SlicerItems(j).Caption)
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fname, _
        Quality:=xlQualityStandard, IgnorePrintAreas:=False, OpenAfterPublish:=False
        Application.DisplayAlerts = True
        MsgBox "File Saved As:" & vbNewLine & "\" & fname, 64, "slicer 1 item#" & IntLoop & " / " & "slicer 2 item#" & j
    Next
Next IntLoop
End Sub
 
Upvote 0
Do you really have this code line, as posted?

Code:
Sheets("").Activate              ' Sheet where the slicers are
 
Upvote 0

Forum statistics

Threads
1,214,428
Messages
6,119,420
Members
448,895
Latest member
omarahmed1

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top