Changing a cell value with VBA (Visual Basic for Applications) in Excel is a straightforward task. Here’s a basic introduction to how you can achieve this:
Change a Specific Cell’s Value
To change the value of a specific cell, you can use the following code:
' Change the value of cell A1 in the active sheet to "Hello"
ActiveSheet.Range("A1").Value = "Hello"
When you run this VBA macro, it will change the value of cell A1 in the active worksheet to “Hello.”
Change a Cell’s Value Based on Another Cell’s Value
Suppose you want to change the value of a cell based on the value of another cell. Here’s an example:
' If cell A1 contains the word "Test", then change cell B1 to "Success"
If ActiveSheet.Range("A1").Value = "Test" Then
ActiveSheet.Range("B1").Value = "Success"
When run, if cell A1 has the value “Test”, then B1 will be changed to “Success.”
Using Cell References
Instead of referencing a cell by its address (like “A1”), you can also use row and column indices. For instance,
Cells(1, 1) refers to cell A1.
' Change the value of cell A1 (Row 1, Column 1) to "World"
ActiveSheet.Cells(1, 1).Value = "World"
How to Run the VBA Code
ALT + F11to open the VBA editor in Excel.
- Insert a new module by right-clicking on any existing module on the left or on the VBAProject, then select
- Paste the VBA code into this module.
- Close the VBA editor.
- Run the macro by pressing
ALT + F8, selecting the macro from the list, and clicking “Run.”
Remember to save your Excel file as a macro-enabled workbook (
.xlsm extension) if you want to save and later run the VBA macros.