How can I select data range for a chart from different sheet using VBA? Suppose that data sheet name is data_sheet
, chart sheet name is chart_sheet
, and my data range is A1:A20
. How can I do this in excel? I checked THIS but didn't work for different sheets. Otherwise, I checked THIS but returned this error: Subscript out of range
:
With Worksheets("chart_sheet")
ActiveChart.SetSourceData Source:=Worksheets("data_sheet").Range("A1:A20")
End With
Assuming "chart_sheet"
is the name of your Chart
and "data_sheet"
is the name of your Worksheet
, I think you want to do the following:
Charts("chart_sheet").SetSourceData Source:=Worksheets("data_sheet").Range("A1:A20")
Your With
block was not doing anything useful - the purpose of a With
block is to allow you to just type .
as a shortcut for something like Worksheets("data_sheet").
.
So something like:
With Sheets("chart_sheet")
.SetSourceData Source:=Worksheets("data_sheet").Range("A1:A20")
End With
would work, because the .SetSourceData
is an abbreviation of Sheets("chart_sheet").SetSourceData
. (Notice also that the Sheets
collection contains both Worksheets
and Charts
objects, so Charts("chart_sheet")
and Sheets("chart_sheet")
both point to the same thing.)
ActiveChart
refers to the currently active chart, just as ActiveSheet
returns to the currently sheet. If you don't have a chart active when that piece of code executes, you will get an error.
So the following piece of code would also probably have worked for you:
Sheets("chart_sheet").Activate
ActiveChart.SetSourceData Source:=Worksheets("data_sheet").Range("A1:A20")
由于chart_sheet可能不是工作表,您尝试过吗?
with sheets("chart_sheet")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.