简体   繁体   中英

How to get a range of cells in excel vba taking data from other sheet?

I'm trying to get data for a graph in a sheet of an excel workbook using VBA. Range of data I need is in the same workbook but in a different sheet.

I need to write that range in cells format, because the column is not always the same, it changes in every execution, I mean:

Range(Cells(3,5),Cells(3,column).value

The problem appears when I take data from other sheet.

If I write:

ActiveChart.SeriesCollection(1).Values = ActiveSheet.Range(Cells(3,5),Cells(3,column).Value

I have no problem, everything's ok. But when I take data from other sheet:

ActiveChart.SeriesCollection(1).Values = Sheets("Data").Range(Cells(3,5),Cells(3,column).Value

I get a

Run-time error '1004': Application-defined or object-defined error

This only happens when I use the Cells format to specify a range. If I use the format Range("E5:J5").Value I have no problem with the sheet of the data but in this format I can't or don't know how to specify the column in each execution.

You get the error because Cells is not properly qualified. Meaning, in this bit of code,

Sheets("Data").Range(Cells(3,5),Cells(3,column)).Value

what you are implicitly saying is

Sheets("Data").Range(ActiveSheet.Cells(3,5),ActiveSheet.Cells(3,column)).Value

which clearly makes no sense, because ActiveSheet is a different sheet than Sheets("Data") .

You can do this instead:

Sheets("Data").Range("E3").Resize(1, rangeWidth).Value

In your specific case, you can replace rangeWidth with column - 4 since column E is column 5.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM