Every object has properties. For example, a Range object has a property called Value. You can write VBA code to display the Value property or write VBA code to set the Value property to a specific value. Here's a procedure that uses the VBA MsgBox function to pop up a box that displays the value in cell A1 on Sheetl of the active workbook:
Msgbox Worksheets("Sheet1").Range("A1").Value End Sub
MsgBox is a useful function that you'll use often to display results while your VBA code is executing. I use it extensively throughout this book.
The code in the preceding example displays the current setting of the Value property of a specific cell: cell A1 on a worksheet named Sheetl in the active workbook. Note that if the active workbook does not have a sheet named Sheetl, the macro will generate an error.
Now, what if you want to change the Value property? The following procedure changes the value displayed in cell A1 by changing the cell's Value property:
Worksheets("Sheet1").Range("A1").Value = 123 End Sub
After executing this routine, cell A1 on Sheet1 has the value 123. You might want to enter these procedures into a module and experiment with them.
Most objects have a default property. For a Range object, the default property is the Value property.Therefore,you can omit the .Value part from the above code,and it will have the same effect. However, it's usually considered good programming practice to include the property, even if it is the default property.
Was this article helpful?