[英]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. 我正在尝试使用VBA在Excel工作簿的工作表中获取图形的数据。 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
运行时错误“ 1004”:应用程序定义或对象定义的错误
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. 如果我使用
Range("E5:J5").Value
格式,则数据表没有问题,但是以这种格式,我不能或不知道如何在每次执行中指定列。
You get the error because Cells
is not properly qualified. 因为
Cells
资格不正确,您会收到此错误。 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")
. 这显然没有任何意义,因为
ActiveSheet
与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. 在您的特定情况下,因为
E
列是第5列,所以可以用rangeWidth
column - 4
列替换rangeWidth
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.