Quantcast
Channel: An Excel Blog For The Real World
Viewing all articles
Browse latest Browse all 117

How To Trigger Your VBA Macros To Run Based On A Specific Cell Value Change

$
0
0
How To Trigger Your VBA Macros To Run Based On A Specific Cell Value Change

Today we are going to discuss how you can automatically make your VBA code execute based on a specific cell value being changed. Behind the scenes, Excel keeps track of specific events that occur while the user is working on their spreadsheet. These tracked events are called Event Handlers and we can use Event Handlers as triggers to kick off our macros based on what our users are doing to their spreadsheets.

What Are Some Examples of Event Handlers?

There are a bunch of Event Handlers available to you and they fall into two categories: Workbook and Worksheet Events. What the handlers capture is fairly evident by their names, so I won't go into detail on what each on does. But I will go ahead and list some of them out so you can have an idea of what is available to you.


Workbook Events

  • Open
  • SheetChange
  • SheetActivate
  • BeforeClose
  • BeforeSave
  • NewChart

Worksheet Events

  • Change
  • Activate
  • BeforeDelete
  • BeforeDoubleClick
  • BeforeRightClick
  • SelectionChange

Where Are Event Handlers Located?

Event Handlers are not stored in your typical module location. They are actually stored inside either your Workbook or Worksheet object. To get to the "coding area" of either your workbook or worksheet, you simply double-click ThisWorkbook or the sheet name (respectively) within your desired VBA Project hierarchy tree (within the Project Window of your Visual Basic Editor).

How Do I Add An Event Handler?

Event Handlers have very specific subroutine names and variables. It is very important not to have any typos within the sub name or the variables it declares. To guarantee avoidance of any typos, I always recommend having the Visual Basic Editor set up the Event Handler code for you. To do this,  select either Worksheet or Workbook from the Object drop-down box and then select the Event Handler you wish to use from the Procedure drop-down box.

VBA Event Handler Trigger Macro Code

Let's Walk Through An Example!

Hopefully, you now have some sort of conceptual understanding of Event Handlers, but how do you use them in the real world? Let's walk through a very simple example that will allow us to run some VBA code whenever the Cell G7 contains the word "yes" on our spreadsheet.

Below is going to be our interface where Excel will reveal a joke if you type the word "Yes" into the blank box (Cell G7).

Excel VBA Event Handler Trigger Macro Code

The Example in Action

You can see through the following diagram, immediately after I type in "Yes, tell me a joke!", a super-funny joke magically appears! 

Excel VBA Change Event Handler Trigger Macro Code

The VBA Behind The Spreadsheet

To get this spreadsheet working as intended, I needed to add an Event handler, to capture anytime there was a change to the cell G7. I choose to use the Change Event Handler to make this happen.

What the Change event captures is any change made to your spreadsheet (excluding formatting changes). You'll notice that the Worksheet_Change subroutine has a variable named Target that gets fed into it. This variable is a Range-type and will be the cell that was last changed by the user. So if I changed the value in Cell A1, the Worksheet_Change subroutine would kick off and pass Cell A1 into the Target variable.

With this in mind, we are going to want to test the cell that was changed to see if it matches the cell we are concerned with. We can do this by starting our code off with a very simple If Statement that acts as a door to the rest of the code.

'Determine if change was made to cell G7
  If Target = Range("G7") Then

If the Target cell does not have access to get past the door, then the code ends and it will happen so fast, that your user won't know anything has happened.

Below is the code in full that will test if the word "Yes" was entered into cell G7 anytime a change happens within Sheet1:

'Remove Case Sensitivity
  Option Compare Text

Private Sub Worksheet_Change(ByVal Target As Range)

'Determine if change was made to cell G7
  If Target = Range("G7") Then
    'Determine if the work "yes" is contained within cell g7
      If InStr(1, Range("G7"), "Yes") > 0 Then
        Range("G9").Font.Color = Range("F5").Font.Color
      Else
        Range("G9").Font.Color = Range("G9").Interior.Color
      End If
  End If

End Sub

And here is a diagram of where you would place the code within your VBA Project:

Worksheet Event Handler.png

Why Aren't My Events Getting Captured?

Many people will turn off the tracking of Event to speed up their VBA code. If you are relying on capturing events within your spreadsheet and they don't seem to be working, you can run the following command in the Immediate Window (use the shortcut Ctrl + g to make this window visible) within the Visual Basic Editor.

Just hit your enter key after typing the below phrase into the Immediate Window:

  Application.EnableEvents = True

Get The Example File Used In This Article

Sometimes seeing things in action may help you learn much better than reading about it in an article. That is why I am making the example I walked through in this article available to you. The workbook and its code are completely unlocked so you can dig in and discover how all the magic works.

As always, in order to download this example file you will need to be a subscriber of my free newsletter.  If you click the green button below you can easily sign up and you will be emailed the password to get into the subscribers-only area of this website.

       Already Subscribed? Click HERE to log-in to the "Example Files" section

     Already Subscribed? Click HERE to log-in to the "Example Files" section

 

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it's impossible to account for every particular need one might have. That's why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to getting quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don't have time to fit everyone's questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Chris "Macro" Newman :)


Viewing all articles
Browse latest Browse all 117

Trending Articles