我的代码应为数据库的每一行创建一个图表。该数据库在另一个工作表中。由于该数据库应该更改列数,因此我要计算多少列并更改数据源。每次我运行代码时,SetSourceData中都会出现错误。
我找不到我在做错什么。
有人可以帮我找到解决方案吗?
Sub createColumnChartMatriz12()
Dim ChartName As String
Dim Row As Integer
Dim ChartRow As Integer
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Matriz 1")
Dim k As Long
Dim z As Long
k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count
z = sh.Cells(1, sh.Columns.Count).End(xlToLeft).Column - 4
ThisWorkbook.Sheets("Matriz1Chart").Select
Cells.Select
Selection.RowHeight = 15.5
Cells(1, 1).Select
ChartRow = 49
Row = 2
For Row = 2 To k
ChartName = "Utilização no Período " & sh.Cells(Row, 1).Value
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
With ActiveChart
.SetSourceData Source:=sh.Range(Cells(Row, 4), Cells(Row, z)), _
PlotBy:=xlRows
.FullSeriesCollection(1).XValues = "='Matriz 1'!$D$1:$AM$1"
.Parent.Height = Range("A1:A15").Height
.Parent.Width = Range("A1:J1").Width
.Parent.Top = Range("A" & ChartRow).Top
.Parent.Left = Range("A" & ChartRow).Left
.HasTitle = True
.ChartTitle.Text = ChartName
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Meses"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Utilização"
.Axes(xlCategory, xlPrimary).TickLabels.NumberFormat = "mm-yyyy"
End With
ChartRow = ChartRow + 16
Next
End Sub
答案 0 :(得分:0)
不确定这是否是您唯一的问题,但是当您通过提供两个单元格(单元格实际上也是范围)访问“范围”时,您也必须限定这些单元格。
您的语句sh.Range(Cells(Row, 4), Cells(Row, z))
试图定义工作表Range
的{{1}}对象(保存在变量"Matriz 1"
中),但是sh
引用了有效的表。这会使范围本身无效,并导致Cells(Row, 4)
命令失败。
您应该改写.SetSourceData
。作为一般建议:分解这种复杂命令的逻辑-调试和找出失败原因要容易得多。在您的情况下,首先定义范围,将其写入变量,然后将其分配给图表:
sh.Range(sh.Cells(Row, 4), sh.Cells(Row, z))
或者,如果您愿意(但请注意开头的With ActiveChart
dim chartRange as Range
set chartRange = sh.Range(sh.Cells(Row, 4), sh.Cells(Row, z))
.SetSourceData Source:=chartRange, PlotBy:=xlRows
...
end with
)
.