EDIT: Sub dump_range
below shows that the address does not completely define a Range
(as far as operating with its contents is concerned), something that I found surprising, and not clearly stated in MS documentation. There is something else, a "subtype". It appears that one cannot inquire about the "subtype", but only indirectly, via Count
. The practical relevance of this point is that, if one defines a Sub
(or Function
) taking a Range
as an argument, one should bear this in mind to code the Sub
(something that I personally did not do) to avoid potential errors.
This question was sparked by this answer to Traversing `Cells` in a `Range`
In the code
Dim rng As Range, rng2 As Range, rng3 As Range
Set rng = Selection
Set rng2 = rng.Cells
Set rng3 = rng.Rows
(Question 1) what are the differences between objects rng
, rng2
, etc.?
I do not mean to get it explained only in words, but in terms of specification of what methods/properties and results are available for each, and make up the difference among the "subtypes". There should be some, as VBA works differently on them. But I do not find the specification. Actually, the Excel help for the Range.Cells Property is confusing to me: "Returns a Range object that represents the cells in the specified range." It looks to me that it should return the same object as the caller. Links to authoritative documentation will support an explanation.
One can see that there are some differences among the objects by using
Call dump_range(rng) ' -> Range $A$1:$B$6, count = 12
Call dump_range(rng2) ' -> Range $A$1:$B$6, count = 12
Call dump_range(rng3) ' -> Range $A$1:$B$6, count = 6
with
Sub dump_range(ByRef rng As Range)
Debug.Print "Range " & rng.Address & ", count = " & rng.Count
End Sub
(Question 2)
I also want to know if one can test a Range
object for which "subtype" it is.
E.g., how would one discern the "subtypes" of objects rng
and rng2
, without inspecting the code?
I.e., obtaining such information at run-time.
(Question 3) Is there a canonical word for "subtype"?