'Why does Range.Cell fail at the first declaration, but not the second?

I'm trying to figure out a 1004 error I'm getting in my Excel macro. The line for set numRange fails if I use the Range(Cells()) format, but succeeds if I use an explicit Range call (i.e. Range("b2")).

Further down the function, I use the same format (and the same variable name), and it works like a charm.

Any help would be appreciated!

Function GetCopyRange(wbName, wsIndex, vnIndex)
    Dim rowsCounter As Integer
    Dim numRows As Integer
    Dim numCols As Integer
    Dim numRange As Range
    
    rowsCounter = 6 'GetStartCell()
    
    Set numRange = Workbooks(wbName).Worksheets(wsIndex).Range(Cells(rowsCounter, 2)) 'This line fails

    [ ... ]

    Set GetCopyRange = Workbooks(wbName).Worksheets(wsIndex).Range(Cells(rowsCounter, 3), Cells(numRows, numCols)) 'This line succeeds
End Function

Edit: The error I'm getting is a "1004", Application-defined or object-defined error



Solution 1:[1]

Set numRange = Workbooks(wbName).Worksheets(wsIndex).Range(Cells(rowsCounter, 2)) 'This line fails

Workbooks(wbName).Worksheets(wsIndex).Range(

is all well and good. It specifies a range object of the specified worksheet.

Cells(rowsCounter,2)

however, is referring to the cells property of the active worksheet not that of wsIndex.

Like BigBen stated, it is best to specify the range object utilizing the cells property of the worksheet.

Set numRange = Workbooks(wbName).Worksheets(wsIndex).Cells(rowsCounter,2)

I also find it useful to specify the argument types when defining functions as well as the expected return type.

Function GetCopyRange(wbName as String, wsIndex as Integer, vnIndex as Integer) As Range

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ClintK