0
votes

This code is working properly:

Sub test_range()
Dim Range1 As Range
Set Range1 = Sheet4.Range("B2:F6081")
End Sub

When I change the range into variable it gives me error 1004:

Sub test_range()
Dim Range1 As Range
Set Range1 = Sheet4.Range(Cells(2, 2), Cells(6081, 6))
End Sub

What is wrong with my "selecting cells" conversion?

Furthermore, I would like to apply it onto vlookup function:

For C = 2 To ColNumber

    C4 = C + 4
    For R = 2 To RowNumber
        Set Condition = Sheet1.Cells(R, 2)
        'MsgBox (Condition)
        Set Range1 = Sheet4.Cells(2, 2).Offset(6079, C + 3) 'B2 (row 2 column 2) : F6081 (row 6081 column 6)
        'MsgBox (Range1)
            arg1 = 5
            arg2 = False
        Sheet1.Cells(R, C4).Value = Application.WorksheetFunction.VLookup(Condition, Range1, 5, 0)
    Next R

Next C

I tried to modify range into

Range1 = Sheet4.Cells(2, 2).Offset(6079, C + 3)

The range function worked, but the vlookup function (again) gave me error 1004

I read some cases for vlookup and every one dim result of vlookup as a variant. Should I do that also? Can't I just put the result of it onto a value of a column?

1
On your first problem: Cells means ActiveSheet.Cells! Therefore, if your active sheet is not Sheet4, Sheet4.Range(Cells(... will give you an error! Use Sheet4.Range(Sheet4.Cells instead. Or even better Sheet4.Cells(2,2).Resize(6080,5) - Peter Albert
it works well for both, range and vlookup function. THANKS A LOT - Whisnuraga Putra
great! I posted it as an answer. If it solved your problem, please mark it as the answer then! Thanks - Peter Albert

1 Answers

1
votes

Cells means ActiveSheet.Cells! Therefore, if your active sheet is not Sheet4, Sheet4.Range(Cells(... will give you an error!

Use Sheet4.Range(Sheet4.Cells instead.

Or even better, use Sheet4.Cells(2,2).Resize(6080,5)