How to use Range variable? (rudimentary)

C

curiousgeorge408

Sigh, I always seem to have trouble gronking VBA syntax and
semantics. I am sure I have seen examples of the following before,
even in my reference book. But I cannot find them now.

I would like to write something like:

Sub doit()
Dim rng As Range
rng = Range("A1:B4")
For i = 1 To rng.Count: Debug.Print rng.Cells(i): Next i
End Sub

That works if I comment out "rng=..." and replace "rng" with Range
("A1:B4") everywhere. But I get a runtime error on the assignment
statement ("object variable not set").


PS: The above is a distillation of a larger problem. Please do not
offer alternatives to programming the algorithm. I am trying to
understand a language concept, not a programming concept.
 
J

Jim Thomlinson

A range is an object so you need to use the Set key word to assign to it.

set rng = Range("A1:B4")
 
C

curiousgeorge408

A range is an object so you need to use the
Set key word to assign to it.

set rng = Range("A1:B4")

Hugely! Very many thanks.

Now that you mentioned it (again; I'm sure I've seen this answer
before), I scoured Walkenbach's book for any reference to it.

I could not find anything about Set in the index -- nothing under Set,
Object, Range, Assignment Statement.

Finally, armed with your information, in the pages referred to in the
index under Object Variables, I found one example and one sentence
(plus a Tip). Now that I know what to look for, flipping through the
book, I do find a few scattered examples that also use the Set
statement.

Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top