【问题标题】:Loop through all charts in a workbook with VBA使用 VBA 遍历工作簿中的所有图表
【发布时间】:2022-01-19 15:01:08
【问题描述】:

我正在尝试遍历工作簿中的所有图表。 为什么选项 1 有效,而选项 2 无效?

'选项 1

For Each sht In ActiveWorkbook.Worksheets
    For Each cht In sht.ChartObjects
        MsgBox (cht.Name)
    Next cht
Next sht

'选项2

Dim oChart As Chart
    For Each oChart In Application.Charts
        MsgBox (oChart.Name)
    Next oChart
End Sub

【问题讨论】:

  • 选项 1 列出所有 嵌入图表(即任何工作表中包含的图表 - 请参阅 here),而选项 2 列出所有 图表表(见here

标签: excel vba loops charts foreach


【解决方案1】:

图表有两种风格:

  1. “大”图表 - 整个图表表
  2. “小”图表 - 嵌入工作表中的图表对象

这段代码:

Sub dural()
    Dim oChart As Chart
    For Each oChart In Application.Charts
        MsgBox oChart.Parent.Name & vbCrLf & oChart.Name
    Next oChart
End Sub

将显示有关“大”品种的信息。

如果您想了解“小”图表的信息:

Sub dural2()
    Dim sh As Worksheet, i As Long
    For Each sh In Worksheets
        If sh.ChartObjects.Count > 0 Then
            For i = 1 To sh.ChartObjects.Count
                MsgBox sh.ChartObjects(i).Chart.Name
            Next i
        End If
    Next sh
End Sub

请注意,我们需要一个显式的If 语句来处理没有图表的工作表,.Chart 用于访问每个 ChartObjects 列表中的图表。

【讨论】:

    【解决方案2】:

    作为the documentation statesApplication.Charts 返回一个包含所有图表工作表(不是图表!)的Sheets 集合。但是,对于 Worksheet.ChartObjectsthe documentation says 会返回一个包含该工作表上所有图表的 ChartObjects 集合。

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 1970-01-01
      相关资源
      最近更新 更多