Excel VBA – Constants and Cell References

One of the techniques I have found very useful in writing Excel VBA code is to make the cell, row, and column references public constants rather than hard coding them.

Take a reference to a row and column:

cells(4,27).value

If row 4 is the first data row and column 27 is the last column in the list, it is more useful to make them constants and refer to the constant:

Public Const intFirstDataRow As Integer = 4
Public Const intLastRow As Integer = 27

And then make the above reference:

cells(intFirstDataRow, intLastRow).value

This way, when you add a couple of columns or move the first data row down, you change the constant once and the code all works the first time.

Searching and replacing 27 with 31 is fraught with problems since it is too easy to change values or longer numbers (12734 to 13134) inadvertently.


Leave a Reply

Your email address will not be published. Required fields are marked *