**What are constant values in VBA?**

In the previous chapter of the training you learned what are the VBA variables appearing in our VBA code. The difference between variables and constants of VBA is such that the values assigned to constants will not change during the launch of our program. If we want our code to be fully compliant with the principles of good programming and create a compact, coherent whole, then for the constants entered into the code, we should use a separate declaration type. We use the definition of **Const** . We must assign the value for the constant immediately after declaring it. It will not be possible to change it in subsequent blocks of code. Below is an example of declaring the number Pi and the number Euler as constant VBA. Importantly, the data type has been specified. However, it is not required when declaring VBA constants.

1 2 3 4 5 6 7 8 |
Sub ConstDef() Const dubPi As Double = 3.14 Const dubEuler As Double = 2.72 MsgBox (dubPi) MsgBox (dubEuler) End Sub |

**An example with the use of constants**

Let’s create a short program that, after entering the radius of a circle, will calculate its field. Apply the InputBox and MsgBox windows for this purpose.

1 2 3 4 5 6 7 8 9 |
Sub ConstExample() Const dblPi As Double = 3.14 Dim dblRadius As Double dblRadius = InputBox("Wprowadź promień koła: ") MsgBox dblPi * dblRadius ^ 2 End Sub |

In the above example, we introduced the number of PI into the VBA code, assigning it a constant value of 3.14. This number can also be entered into the program using the Excel spreadsheet function. To do this, we use the **Application.WorksheetFunction.NAME_FUNCTION ** command that allows us to use the sheet functions. We must do the action in this case bypassing the constants.

1 2 3 4 5 6 7 8 9 10 |
Sub ConstExample1() Dim dblPi As Double Dim dblRadius As Double dblPi = Application.WorksheetFunction.Pi() dblRadius = InputBox("Wprowadź promień koła: ") MsgBox dblPi * dblRadius ^ 2 End Sub |

**Tasks (You can enter the solution in a comment)**

- Using the Range or Cells command, modify the example and calculate the circle field by taking the radius value from the cells of the sheet. The result itself should also appear in the sheet.
- Using solids, create a program based on the InputBox and MsgBox windows and calculate the circumference of the circle with radius 10. As a reminder, the pattern on the perimeter Ob. = 2 * Pi * R

More examples of Excel VBA basics can be found in the Excel VBA Course section and Excel VBA How To section. If you have any questions about this chapter, you can post them on the forum without logging in.

## Leave a Reply