Constant values in VBA Excel programming

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.


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.

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.



Tasks (You can enter the solution in a comment)

  1. 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.
  2. 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 comment

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

%d bloggers like this: