Adding and executing VBA code in Excel involves the following steps:
- Open Excel and navigate to the worksheet where you want to insert the VBA code.
- Press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
- In the VBA editor, click on Insert and then choose Module to insert a new module.
- Within the module, you can start writing your VBA code using the VBA programming language.
- Once you have written the VBA code, you can save the workbook to retain the code within it.
- To execute the VBA code, go back to Excel and press Alt + F8 to open the Macros dialog box.
- Select the desired macro (which represents your VBA code) from the list and click on Run.
- The VBA code will then execute and perform the actions specified within it.
Here’s an example of a simple VBA code that adds two numbers and displays the result in a message box:
Sub AddNumbers() Dim num1 As Integer Dim num2 As Integer Dim sum As Integer num1 = 2 num2 = 3 sum = num1 + num2 MsgBox "The sum of " & num1 & " and " & num2 & " is " & sum End Sub
After inserting the above code in a new module, you can execute it as mentioned earlier to see the message box displaying the sum of the numbers.