Question

I would like to know what the pros and cons are for storing a range variable instead of four integers or long variables (representing the first and last row and column) to define that range. One could also use a single-cell range variable in combination with two integers to define the row and column to define a larger range.

Obviously, there are situations where you would need to use one method over the other. But there are also situations where you need both the indices and the range at some point, and there are situations where either method will work (for example if you need to reference each cell in the range one by one).

So I don't need trivial pros and cons like "When you need to change the format of the entire range, reference the range.". Also, I'm only asking about which variable you would use in situations where either ranges or indices will work, or where both are needed at some point.

EDIT: I'm aware that for each will beat nested for loops at code golf in this situation, no need to mention this one or other situational code golf answers because anyone who knows how to use either method should be able to figure that out on their own.

Was it helpful?

Solution

In simple VBA, it is really just a style choice since either will do the job and any performance difference will be negligible. I can only see this question mattering in more complex scenarios.

A few things to consider:

You may need more than four integers to specify a range. A full reference to a single cell would require a file name, a worksheet name, a row, and a column.

If you change the layout of a worksheet, it may be simpler to redefine the range once at the beginning of your function rather than to change integer values in several places.

A range can contain multiple areas. For example, you could have four cells over here and a four non-contiguous cells over there defined by one range object.

If you are doing several things to each cell (say retrieving a value, setting color, setting border, setting number format), it could be better to use a range variable (telling Excel "this spot, do this") rather than repeatedly telling Excel to "go find this sheet/row/column, do this".

If you were calling Excel from the outside using COM Automation, there may be an advantage to making your interface clearer by returning a range object (already defined in a type library) rather than an array or other user-defined data structure (that you have to define an interface for, publish a type library, or apply a custom marshaling attribute).

Licensed under: CC-BY-SA with attribution
scroll top