如何在vba中向Chart数组中添加元素

时间:2017-05-24 00:02:40

标签: arrays vba excel-vba charts excel

我正在尝试将14个散点图添加到新工作簿中的图表工作表中。以下代码不会将新图表存储在动态数组中。

   Sub GenerateViewSheets()

   Dim curBook As Workbook
   ' Create new worksheet
   Dim NewBook As Workbook
   Set NewBook = Workbooks.Add

   'Add a sheet
   Dim chrt As Chart
   Set chrt = NewBook.Charts.Add(Before:=Worksheets(Worksheets.Count))
   chrt.Activate

   'Add charts   
   Dim nCharts As Integer
   Dim iChrt As Integer
   Dim chartArray() As Chart
   nCharts = 14
   ReDim chartArray(1 To nCharts) As Chart

   With chrt
      For i = 1 To nCharts
         Set chartArray(i) = .ChartObjects.Add(1, 1, 20, 20) ' Left, Top, Width, Height
      Next i
   End With
   End Sub

错误消息是

  Error #  13
  Generated by VBAProject
  Error Line: 0
  Error Desc: Type mismatch

1 个答案:

答案 0 :(得分:1)

将数组类型更改为ChartObject:

   Sub GenerateViewSheets()

   Dim curBook As Workbook
   Dim NewBook As Workbook

   Set NewBook = Workbooks.Add

   'Add a sheet
   Dim chrt As Chart
   Set chrt = NewBook.Charts.Add(Before:=Worksheets(Worksheets.Count))
   chrt.Activate

   'Add charts
   Dim nCharts As Integer
   Dim iChrt As Integer
   Dim chartArray() As ChartObject

   nCharts = 14
   ReDim chartArray(1 To nCharts) As ChartObject

   With chrt
      For i = 1 To nCharts
         Set chartArray(i) = .ChartObjects.Add(1, 1, 20, 20) ' Left, Top, Width, Height
      Next i
   End With

End Sub