VBA Refer to worksheet vs chart sheet

﹥>﹥吖頭↗ 提交于 2019-11-30 05:19:55

问题


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.


回答1:


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

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




回答2:


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


来源:https://stackoverflow.com/questions/6797427/vba-refer-to-worksheet-vs-chart-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!