Dale, there is more than one cell in the named range. In your example, if 'num1' was A1:A10, how would you get the values of each cell in 'num1'?
Thanks
-Nat
To get the values of all the cells in a named range, use the For Each statement, like this ...
Option Base 1
Sub Cell_To_Variable()
Dim myvar()
For Each c In ThisWorkbook.Sheets(1).Range("var1"
vcount = vcount + 1
ReDim Preserve myvar(vcount)
myvar(vcount) = c.Value
Next
End Sub
You can refer to an individual cell in a range using range(rowindex, colindex), like so:
Dim r As Range
Dim s As String
Set r = Range("Test"
i = r(3, 2).Value
MsgBox s
This gives you the value of the cell that's 3 down in the range, and 2 across. Bizarrely, you can extend *outside* the named range: even if the range Test is only 3 by 2, r(7,7) will work perfectly well. If you need to limit yourself to cells really within the range, then use the For each c in r routine described in an earlier post
Thank you both for the useful info. But listen to this. I stumbled upon this by 'mistake'. If you have a variant it will 'take' the entire range (multiple dimensions too!) with a simple "variant = range" statement!
Suppose a named range "test" covers A1:A10.
Dim vTest As variant
vTest = Range("test". <------- 1 line does it!
Suddenly vTest becomes an array, in this case 2 dimensions (don't know -or care- why) and the values of A1 thru A10 are in vTest(1,1) thru vTest(10,1).
Note, that this holds true ragrdless if vTest was DIM'd as an array (Dim vTest() as Variant) or simply Dim'd as in the example above.
Hey, is this interesting stuff, or what? Worth a FAQ, or is it common knowladge?
It uses the Variant type, which is b-a-d (and disappears in VB.NET); and
You can't extend beyond the limits of the named range (you get a "Subscript out of range" error)... although admittedly this might be a good thing, since it enables you to ensure that you only address the cells within the range; and
You can't get at any other properties of the cell except its value - no good if you want to add them all up and format the biggest ones in red or something (ie, you can't do something like var(1,1).font).
But all that's just sour grapes because I didn't actually know the trick you've found!
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.