Sometimes we create a Macro but we don’t want trigger it by Run Macro via Developer->Run Macro or other keyboard shortcuts. We may set the trigger by clicking a specific cell like click A1 or E1 for example. Once we clicking on the specific cell A1 or E1, the Macro will run properly, it looks verify convenient. So, in this article we will help you to trigger a macro by clicking cell via VBA.
First, create a Macro “DeleteAllCharts” which is used for remove all charts on worksheet.
We create a table with two different type of charts. See screenshot below.
Edit VBA script to remove all charts for current worksheet, see VBA script below. The Macro name is “DeleteAllCharts”. Let’s started to learn how to trigger a macro by a specific cell now.
Trigger A Macro by Clicking A Specific Cell in Excel
Step 1: Right click on Sheet1 to load Sheet management menu. Select View Code, Microsoft Visual Basic for Applications window pops up.
Or you can enter Microsoft Visual Basic for Applications window via Developer->Visual Basic.
Step 2: In Microsoft Visual Basic for Applications window, click on Sheet1, enter below code:
Option Explicit Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Selection.Count = 1 Then If Not Intersect(Target, Range("D2")) Is Nothing Then Call DeleteAllCharts End If End If End Sub
Comment:
In above script, D2 is the cell for trigger the Macro, DeleteAllCharts is Macro name, you can replace above two parameters by your own parameters. In this case, if we click on D2, DeleteAllCharts will be executed, all charts will be removed.
Step 3: Save the codes, see screenshot below. And then quit Microsoft Visual Basic for Applications.
Step 4: Click on D2. Verify that all charts are removed properly. That means macro is triggered by cell D2 properly. You can add some descriptions in D2 to do demonstration, you can also leave D2 as blank, it also works normally if you click on cell D2 without any value entered.