Before coming to ask I searched the web a lot, and the answers I found did not solve the problem. The "Data" Worksheet is in the same Workbook as the "Reports" Worksheet.
This is the part of my code that matters for this question:
Private Function CreateChart(ByVal DataRow As Integer, ByVal DataCol As Integer)
Dim ChartRowOffset As Integer
Charts.Add
ActiveChart.ChartType = xlPie
ActiveChart.SetSourceData Source:=Sheets("Data").Range(Cells(2, DataCol), Cells(DataRow - 1, DataCol + 1)), PlotBy:=xlColumns
ActiveChart.Location Where:=xlLocationAsObject, Name:="Report"
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = ThisWorkbook.Sheets("Data").Cells(1, DataCol).Value
If DataCol > 1 Then
ChartRowOffset = (DataCol - 1) * 2
Else
ChartRowOffset = 2
End If
With ActiveChart.Parent
.Top = ThisWorkbook.Sheets("Report").Cells(ChartRowOffset, 1).Top
.Left = ThisWorkbook.Sheets("Report").Cells(ChartRowOffset, 1).Left
End With
End Function
I am getting error code 1004 "Application-defined or Object-defined error" when I try to select a source from a different worksheet in this line:
ActiveChart.SetSourceData Source:=Sheets("Data").Range(Cells(2, DataCol), Cells(DataRow - 1, DataCol + 1)), PlotBy:=xlColumns
If I do it without Sheets("Data"), it gives no error and creates the chart, but it selects cells from the "Reports" sheet, not the Worksheet I need. I tried selecting the "Data" Worksheet, activating it, nothing worked so far.
Any help would be appreciated.
Cells
to define aRange
as you're mixing A1 and R1C1 ReferenceStyles. You can, however, continue with your method with this change -ActiveChart.SetSourceData Source:=Sheets("Data").Range(Cells(2, DataCol).Address, Cells(DataRow - 1, DataCol + 1).Address), PlotBy:=xlColumns