Jesse Smothermon
Jesse Smothermon

Reputation: 1051

VBA Refer to worksheet vs chart sheet

I'm trying to write a small function that takes in a filepath (where the workbook was saved at), targetpath (where the pdf will be saved to), and a string of tab names (pipe (|) delimited) in excel.

The user of the function doesn't have to input a string of tab names (it's optional) and if they don't, I want to select all of the visible tabs and print them. This would be in the case if the user has 50 charts in separate worksheets and don't want to write a string like "Chart1|Chart2|...."

Code:

For Each WSO.Name In WBO.Worksheets 
    strSheets = strSheets & WSO.Name & "|" 
Next WSO

strSheets = Left(strSheets, Len(strSheets) - 1) 
arraySheets() = Split(strSheets, "|")

WBO.Sheets(arraySheets()).Select     
WBO.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _ 
    strFilePath, Quality:=xlQualityStandard, _ 
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _ 
    True

There's two problems with the For Each loop: it doesn't grab any sheets such as "Chart1", it only grabs sheets such as "Sheet1". Also, it will grab hidden sheets so that when I try to select them all I get an out of bounds error.

I didn't know if a Chart sheet is referred to differently then a regular sheet or why hidden sheets are also chosen.

Upvotes: 6

Views: 20078

Answers (2)

Steve Rindsberg
Steve Rindsberg

Reputation: 3528

There's two problems with the For Each loop: it doesn't grab any sheets such as "Chart1", it only grabs sheets such as "Sheet1"

Charts and Worksheets are two different collections.
Try this:

Sub Demo()
Dim oWs As Worksheet
Dim oCs As Chart

For Each oWs In ActiveWorkbook.Worksheets
    Debug.Print oWs.Name
Next

For Each oCs In ActiveWorkbook.Charts
    Debug.Print oCs.Name
Next
End Sub

Upvotes: 7

GSerg
GSerg

Reputation: 78185

Use WBO.Sheets instead of WBO.Worksheets in the loop.

Verify that WSO.Visible = xlSheetVisible to filter out hidden sheets.

Upvotes: 8

Related Questions