If you need to use the value that never changes, it will be wise to use a constant instead of a variable. When you use the constant you can be sure that the value is always the same and you won’t accidentally change it to a different one. If you try, Excel will return an error.
You can declare constants by using the Const word at the beginning.
Const monthsInYear As Integer = 12
Const PI As Double = 3.141593
Excel VBA Constants
Besides user-defined constants, Excel offers many predefined ones. You can meet them when you use the macro recorder.
Look at the following code generated by the macro recorder. It fills a cell with yellow color.
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
Insert MsgBox(xlAutomatic) before End With.
If you execute the macro it will display the message showing the value assigned to constant xlAutomatic.
If you write .PatternColorIndex = -4105 instead of xlAutomatic it will give you the same result.
Skillshare’s usually $10 a month, but because you’re an OfficeTuts reader you can get your first month free by clicking here. That’s unlimited access to over 18,000 classes on Excel, VBA, and much more.