I have a workbook with 2 worksheets: sheet1 and sheet2. I am attempting to populate an array (mntharray) from the Range "A6:D10." This range is not fixed and can have more or fewer rows so a formula is used to compute it. Here is the simplified code.
/
Sub test()
Dim mntharray() As Variant
Dim numrows As Integer
Dim sheet1WS As Worksheet
Set sheet1WS = Sheets("Sheet1")
numrows = 5
ReDim mntharray(numrows, 4)
mntharray = sheet1WS.Range(Range("A6"), Range("D" & numrows + 5))
End Sub
/
Here is the issue. If I have the focus on sheet 1 (sheet1 is selected in the Excel worksheet) and I run the code, it runs fine. If the focus is on sheet2, I get the "Run-time" error, Range of object failed.
My understanding is that by defining the object variable sheet1WS, this is sufficient for VBA to determine the reference for mntharray. An important observation is that if the line
mntharray =sheet1WS.Range("A6:D10") the code works as I would expect, regardless of the focus. Obviously, my understanding is wrong and there is a small complexity added with the more complicated formula in mntharray. Can you explain this to me?
/
Sub test()
Dim mntharray() As Variant
Dim numrows As Integer
Dim sheet1WS As Worksheet
Set sheet1WS = Sheets("Sheet1")
numrows = 5
ReDim mntharray(numrows, 4)
mntharray = sheet1WS.Range(Range("A6"), Range("D" & numrows + 5))
End Sub
/
Here is the issue. If I have the focus on sheet 1 (sheet1 is selected in the Excel worksheet) and I run the code, it runs fine. If the focus is on sheet2, I get the "Run-time" error, Range of object failed.
My understanding is that by defining the object variable sheet1WS, this is sufficient for VBA to determine the reference for mntharray. An important observation is that if the line
mntharray =sheet1WS.Range("A6:D10") the code works as I would expect, regardless of the focus. Obviously, my understanding is wrong and there is a small complexity added with the more complicated formula in mntharray. Can you explain this to me?