Overview
Have you ever wanted to automatically execute a macro just by selecting a specific cell in Excel?
This article introduces how to create a VBA macro that runs a program automatically when you place the cursor on cells G2 to G100.
- Displays a dialog when a specific cell is selected.
- Executes the process only if “Yes” is selected.
- Can be replaced with any processing logic.
This type of “Event-Driven VBA” works in response to user actions, making it useful for creating form-like behaviors.
Specifications
- Target: Cells G2 to G100.
- Trigger: When a target cell is selected, a confirmation dialog (“Do you want to run the program?”) appears.
- Action: If “Yes” is clicked, the specified program runs.
Implementation Steps
1. Write Code in the Worksheet Module
First, open the VBA Editor. In the “Microsoft Excel Objects” list on the left, double-click the Worksheet (e.g., Sheet1) where you want the code to run.
Paste the following code directly into the window.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Check if the selection change occurred within the range G2 to G100
If Not Intersect(Target, Me.Range("G2:G100")) Is Nothing Then
' Show confirmation message
Dim MsgResponse As VbMsgBoxResult
MsgResponse = MsgBox("Do you want to run the program?", vbQuestion + vbYesNo, "Confirmation")
If MsgResponse = vbYes Then
' ↓ Write the program you want to execute here
MsgBox "Program executed.", vbInformation
End If
End If
End Sub
How to Customize the Program
The line MsgBox "Program executed.", vbInformation is just a placeholder. You should replace this line with your own processing logic, such as calling another macro, file operations, or writing to cells.
Example:
If MsgResponse = vbYes Then
Call MyCustomMacro ' Call a macro defined in a standard module
End If
Important Notes
- Accidental Triggers: Since the macro runs every time a cell in column G is selected, be careful when editing data in that column.
- Control: If you want to limit the execution (e.g., run only once), you may need to implement a flag management system.
Summary
To automatically run a macro when a specific cell is selected, use the Event VBA (SelectionChange).
- This example targets cells G2–G100 and uses a safety design that asks for confirmation before running.
- The execution logic can be customized freely.
You can use this technique to replace buttons or speed up routine tasks, further improving your efficiency in Excel.
