Set Range for VLOOKUP

music_al

Board Regular
Joined
Nov 26, 2008
Messages
133
Hi

Im trying to set a range to be used in a VLOOKUP function. I cant figure out why this isn't working...
The RowCount variable is holding an Integer.

Code:
Dim MyRange as Range
Set MyRange = Worksheets("Anysheet").Range(Cells(2, 2), Cells(RowCount,5))

Thank you in advance.
 
You need to qualify the cells like
Code:
Set MyRange = Worksheets("Anysheet").Range(Worksheets("Anysheet").Cells(2, 2), Worksheets("Anysheet").Cells(RowCount, 5))
or slightly simpler
Code:
Dim MyRange As Range
With Worksheets("Anysheet")
   Set MyRange = .Range(.Cells(2, 2), .Cells(RowCount, 5))
End With
 
Upvote 0
When the code runs, is "Anysheet" the activesheet? I think the issue is being caused by Cells(2,2) and Cells(RowCount, 5) not knowing what sheet they belong to.

Below works for me, regardless of which sheet is active, check difference in syntax to yours:
Rich (BB code):
Sub test()
Dim RowCount As Integer: RowCount = 20
Dim MyRange As Range


Set MyRange = Range(Worksheets("MonkeyTennis").Cells(2, 2), Worksheets("MonkeyTennis").Cells(RowCount, 5))
MsgBox MyRange.Parent.Name & " " & MyRange.Address 'MsgBox displays "MonkeyTennis $B$2:$E$20"

Set MyRange = Nothing
End Sub
PS Integer data types in VBA are virtually redundant, you're better off declaring them as longs
and PPS beaten2it
 
Last edited:
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top