Microsoft Excel Macros


VBA Lesson 19: VBA for Excel Variables

You will start developing complex and sophisticated programs in Excel and you will start working with very large sets of data when you discover the variables.

A variable is an object that you create and in which you can store text, dates, numbers or almost anything else. Why should you use variable? The first good reason is to make your code dynamic, to avoid hard coding some values.

Hard Coding vs Dynamic Coding

You are hard coding when you write:
Workbooks.Open "MyFile.xls"

You are dynamically coding when you enter the name of the file in an cell (A1) of your Excel sheet and you write.
Workbooks.Open varWorkbook

At this point you or the user can change the name of the workbook to open in cell A1 instead of going to the VBA code in the Visual Basic Editor.

You will also create variables to count the number of rows, store the result in a variable and then do something as many time as there are rows.

For varCounter = 1 to varNbRows

In the VBA procedure above the value in each cell is multiplied by 2 then the cell below is selected. This action is repeated as many times as there are rows in the set of data.

Go to the next lesson
20 : VBA for Excel Statements

left arrow Back home