简体   繁体   中英

excel VBA different worksheet Range to Array

I have this code which reads data into an array.

Public Const DATASHEET As String = "Data Entry"

For some reason this works:

Function SomeCalculation(col As Integer) As Double
Dim data_table As Variant
Dim lastrow as Integer

lastrow = Worksheets(DATASHEET).Cells(Worksheets(DATASHEET).Rows.Count, col).End(xlUp).row
data_table = Range(Cells(1, col), Cells(lastrow, col + 5)).Value

But this fails:

Function SomeCalculation(col As Integer) As Double
Dim data_table As Variant
Dim lastrow as Integer

lastrow = Worksheets(DATASHEET).Cells(Worksheets(DATASHEET).Rows.Count, col).End(xlUp).row
data_table = Worksheets(DATASHEET).Range(Cells(1, col), Cells(lastrow, col + 5)).Value

VBA throws an error trying to execute that last line.

The problem with the first code block is of course that my data is stored on another worksheet to the cell where the function is being called.

Does anyone have any ideas why this is failing, and/or an alternative way to achieve the same thing?

Note that the maxrows line works (counts the rows in the right sheet)

Thanks!

try replace

data_table = Worksheets(DATASHEET).Range(Cells(1, col), Cells(lastrow, col + 5)).Value

with

with Worksheets(DATASHEET)
    data_table = Range(.Cells(1, col), .Cells(lastrow, col + 5)).Value
end with

Just fully reference cells:

data_table = Worksheets(DATASHEET).Range( _
  Worksheets(DATASHEET).Cells(1, col), _
  Worksheets(DATASHEET).Cells(lastrow, col + 5)
).Value

Also, use Long instead of Integer - integers are stored as longs anyway in VBA, so they take as much space and just give you more narrow range of numbers.

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