If one cell changes vba excel

I spent a lot of time researching this and learning how it all works, after really messing up the event triggers. Since there was so much scattered info I decided to share what I have found to work all in one place, step by step as follows:

1) Open VBA Editor, under VBA Project (YourWorkBookName.xlsm) open Microsoft Excel Object and select the Sheet to which the change event will pertain.

2) The default code view is «General.» From the drop-down list at the top middle, select «Worksheet.»

3) Private Sub Worksheet_SelectionChange is already there as it should be, leave it alone. Copy/Paste Mike Rosenblum’s code from above and change the .Range reference to the cell for which you are watching for a change (B3, in my case). Do not place your Macro yet, however (I removed the word «Macro» after «Then»):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("H5")) Is Nothing Then
End Sub

or from the drop-down list at the top left, select «Change» and in the space between Private Sub and End Sub, paste If Not Intersect(Target, Me.Range("H5")) Is Nothing Then

4) On the line after «Then» turn off events so that when you call your macro, it does not trigger events and try to run this Worksheet_Change again in a never ending cycle that crashes Excel and/or otherwise messes everything up:

Application.EnableEvents = False

5) Call your macro

Call YourMacroName

6) Turn events back on so the next change (and any/all other events) trigger:

Application.EnableEvents = True

7) End the If block and the Sub:

    End If
End Sub

The entire code:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("B3")) Is Nothing Then
        Application.EnableEvents = False
        Call UpdateAndViewOnly
        Application.EnableEvents = True
    End If
End Sub

This takes turning events on/off out of the Modules which creates problems and simply lets the change trigger, turns off events, runs your macro and turns events back on.

Run a macro in Excel when a specific cell is changed; this also covers when a cell within a range of cells is changed or updated.

Sections:

Run Macro When a Cell Changes (Method 1)

Run Macro When a Cell Changes (Method 2)

Run Macro when a Cell in a Range of Cells is Changed

Notes

Run Macro When a Cell Changes (Method 1)

This works on a specific cell and is the easiest method to use.

Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code. In the window that opens, select Worksheet from the left drop-down menu and Change from the right drop-down menu.
You should now see this:

For more info on creating macros, view our tutorial on installing a macro in Excel.

Excel will actually run the code that we input here each time a cell within the worksheet is changed, regardless of which cell is changed. As such, we need to make sure that the cell that we want to check is the one that the user is changing. To do this, we use an IF statement and, in this example, Target.Address.

Sample code:

This checks if cell A1 was the cell that was changed and, if it was, a message box appears.

This is a very simple and easy-to-use template. Just change $A$1 to whichever cell you want to check and then put the code that you want to run inside the IF statement.

$A$1 refers to cell A1 and the dollar signs are just another way to reference a cell using what’s called an absolute reference. You will always need to include the dollar signs in the cell reference when you use this method.

Target.address is what gets the address of the cell that was just changed.

Get the value of the Cell

You will probably want to reference the new value of the cell that was changed and you do that like this:

Target.Value

To output the new value of the cell in the message box, I can do this:

If Target.Address = "$A$1" Then

    MsgBox Target.Value

End If

Target is the object that contains all of the information about the cell that was changed, including its location and value.

In the below examples you can also use Target to get the value of a cell the same way as here, though it may not be covered in those sections.

Run Macro When a Cell Changes (Method 2)

(Read the Method 1 example for a full explanation of the setup for the macro. This section covers only the code for the second method.)

The second way to check if the desired cell was changed is a little bit more complicated, but it’s not difficult.

If Not Intersect(Target, Range("A1")) Is Nothing Then

    MsgBox "Hi!"

End If

This method uses Intersect(Target, Range(«A1»)) to find out if the desired cell is being changed.

Just change A1 to the cell that you want to check. For this method, you do not need to include dollar signs around the range reference like you did for method 1.

This method uses the Intersect() function in VBA which determines if the cell that was edited «intersects» with the cell that we are checking.

Reference the value of the cell the same way as the first example.

Run Macro when a Cell in a Range of Cells is Changed

This uses the same syntax as the previous example but with a slight modification.

Here, we want to check if a cell that is within a range of cells has been changed; it could be one of many cells.

If Not Intersect(Target, Range("A1:A5")) Is Nothing Then

    MsgBox "Hi!"

End If

This uses Intersect() just like the previous example to find out if one of the desired cells has been changed.

In this example, the message box appears if any cell in the range A1:A5 is changed. All you have to do is change A1:A5 to the desired range.

Notice that you also don’t need dollar signs in the range reference here like you did in the very first example.

Reference the value of the cell the same way as the first example.

Notes

Knowing which cell was edited and what the new value is for that cell is, as you can see, quite simple. Though simple, this will allow you to make interactive worksheets and workbooks that update and do things automatically without the user having to click a button or use keyboard shortcuts to get a macro to run.

Download the workbook attached to this tutorial and play around with the examples and you will understand them in no time!

Similar Content on TeachExcel

Run a Macro when a User Does Something in the Worksheet in Excel

Tutorial: How to run a macro when a user does something in the worksheet, everything from selecting …

Run a Macro when a User Does Something in the Workbook in Excel

Tutorial:
How to run a macro when a user does something within the Workbook in Excel, such as openi…

Automatically Run a Macro When a Workbook is Opened

Tutorial:
How to make a macro run automatically after a workbook is opened and before anything els…

Stop Excel Events from Triggering when Running a Macro

Tutorial: Create a macro that will run without triggering events, such as the Change event, or Activ…

Automatically Run a Macro at a Certain Time — i.e. Run a Macro at 4:30PM every day

Macro: Automatically run an Excel macro at a certain time. This allows you to not have to worry a…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Содержание

  1. How to run a macro when certain cells change in Excel
  2. Summary
  3. More information
  4. How to Tell if a Cell Changed with VBA
  5. What is aВ Worksheet_Change Event?
  6. How do I use this Event?
  7. How do IВ check if the Cell Changed within a Specific Range?
  8. How to avoid infinite loops
  9. VBA Worksheet Change Event – Run a Macro When a Cell Changes
  10. Worksheet_Change Event
  11. VBA Coding Made Easy
  12. VBA Code Examples Add-in
  13. Calling a custom built VBA function when an Excel cell is changed
  14. 1 Answer 1
  15. Explanation

How to run a macro when certain cells change in Excel

Summary

In Microsoft Excel, you can create a macro that is called only when a value is entered into a cell in a particular sheet or in any sheet that is currently open.

Note, however, that you should not call macros unnecessarily because they slow down the performance of Excel.

More information

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. In many instances, a macro should run only when a certain number of cells have values entered into them (referred to as the «key cells» in this document). In order to prevent a large macro from running every time a value is entered into a cell of a sheet, you must check to see if the ActiveCell is one of the key cells. To accomplish this, use the Intersect method on the ActiveCell and the range containing the key cells to verify the ActiveCell is one of the key cells. If the ActiveCell is in the range containing the key cells, you can call the macro.

To create the Visual Basic macro:

Right-click the Sheet1 tab and then click View Code.

The module sheet behind Sheet1 is opened.

Type the following code into the module sheet:

Click Close and Return to Microsoft Excel on the File menu.

When you type an entry in cells A1:C10 on Sheet1, a message box is displayed.

Источник

How to Tell if a Cell Changed with VBA

There are times when you want to run a macro when a cell changed. Maybe you want to do some special calculation when a cell changes. Or maybe you’d like to change the font to all uppercase. Or maybe you want to present your users with more meaningful data validation messages. Whatever the case may be, you can use Excel’s Worksheet_Change event in VBA to help accomplish your automation needs.

What is aВ Worksheet_Change Event?

The Worksheet_Change event is a special event that happens in Excel when a cell (or multiple cells) has changed in a specific worksheet. ThisВ includes when a cell is created, updated, or deleted.

This does not include changes like:

  • Formatting changes (font size, cell size, font/cell color, conditional formatting, etc.)
  • A cell changedВ because the calculation was updatedВ (this is a different event called theВ Worksheet_Calculate event)
  • Selecting a cell (this is another event called Worksheet_SelectionChange event)

Does this article help you? If so, please consider supporting me with a coffee ☕️

How do I use this Event?

Open up the VB Editor ( Alt+F11 in Windows or Tools->Macros->Visual Basic Editor on Mac). In the Project window, you’ll see where the workbook and worksheets are:

Double-click on the Sheet1 object and pasteВ the following code:

This is a very basic example of how to start using the Worksheet_Change event. This method is what’s called an Event Handler, which simply means that “this is the method I want to use for handling when X event happens.”

Whenever a cell changes as we described above,В Excel will execute theВ Worksheet_Change event and pass in the cells that were changed through the target object. We use this target object to take a look at which cells were affected.

To invoke this event, go to the Sheet1 worksheet and make a change to a cell. Then, in the VBE Immediate Window ( Ctrl+G on Windows or in Mac this window should always be visible) you will see some text appear each time the event is fired. Here’s an example:

Notice that whenever I change a cell, the Immediate Window shows some text based on the cell I changed. Also note that if I change multiple values at the same time, like cells A1:A2 , then the target object contains that specific range and not just a single cell or array of cells.

It’s important to note that you can work with a range of cells within the same target object that is passed in to the event handler. We’ll take a look at this in the following sections.

How do IВ check if the Cell Changed within a Specific Range?

The target object is simply a range object that describes which cell changed (or set of cells). As shown before, you can get either a single cell, or multiple cells passed into the range (even several range areas, but that’s a topic for another post).

When you want to see if the items that changed fall within another range, you can use the following code:

Here is an example of how this works:

I use the Intersect() function to determine if the target range is within another range that I defined «A1:B3» . The result of Intersect will beВ the range of cells that intersected, if any. The Intersect() function returns Nothing when no intersection is found. ThisВ is why we check for that in the If statement.

Notice that when I select A2:C4 , the target object has the range A2:C4 , but the intersection range has A2:B3 . This is an important distinction to make when working with an intersection. If you used the target range instead of the intersection range, you may end up working with the wrong data (i.e. cells C2:C4 in this case).

How to avoid infinite loops

Now that you know how to monitor changes in your worksheet and act on them, let’s consider what would happen if you make a change to a cell within the Worksheet_Change event.

Consider the following code:

In the For loop, I go through each cell that was effected and prepend the cell with some text.

However, changing the cell value will cause the Worksheet_Change event to fire again, which will take the new value of the text and again prepend it with some more text, and on and on this will go until either Excel crashes or you close the app.

To avoid this, we have to temporarily disable events from firing, make the change to the cell, then re-enable the events.

Application.EnableEvents is a boolean property that you can read / write. When we set this to False , any events that would normally happen (like a Worksheet_Change event) will be suppressed. When we turn this back to True , we will get the events to happen as we expect.

Wow, you read the whole article! You know, people who make it this far are true learners. And clearly, you value learning. Would you like to learn more about Excel? Please consider supporting me by buying me a coffee (it takes a lot of coffee to write these articles!).

Written by Joseph who loves teaching about Excel.

Источник

VBA Worksheet Change Event – Run a Macro When a Cell Changes

Worksheet_Change Event

You may want to run a macro when a cell changes. A popular use of this ability is to have custom code validate a cell after a change is made. It’s easy to do this by using the worksheet objects change event.

In the Visual Basic Editor you must first double click the sheet name where the cell changes that activates the macro. This opens the code window for that sheet object. In this case I wanted to run a macro when a cell in Sheet1 changes.

After opening the code window for the Worksheet you place your code in the Worksheet_Change event. The following example will display a message box if the contents of cell A1 change. First the subroutine fires if any cell changes, then the use of an IF..Then statement will run the code only if cell A1 was the cell that changed based on the If…Then.

You can place your code directly in the Worksheet_Change subroutine or call another macro from there.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Calling a custom built VBA function when an Excel cell is changed

I’d like to preface this question by saying that I am an undergrad in college who knows C++ and has a very rudimentary understanding of VBA.

Now then, as stated in the title I need some help configuring some VBA code for an Excel worksheet so that whenever a cell in a column (specifically the D column) is modified it will automatically update other cells within the same row.

Essentially I want this to work such that when user Bob modifies cell D26 (for example) it will call a custom function I built and insert that code into cell B26 and then repeat with a different function for cell C26.

However, this function needs to be such that if cell D27 is modified it will only modify other cells in row 27, leaving row 26 and prior or subsequent rows alone until such a time as this function is called in D28 and so on.

I’m not entirely sure if this is even possible but I’d be gracious if anybody could help me configure this.

The code I built/scavenged from the internet for my custom function is this: http://pastebin.com/RE0V2nrT

The second function I want to call for this project is the =TODAY() function built into Excel.

The code I have scraped together so far for checking if the cell has changed is this: http://pastebin.com/S5E8cmty

If anybody could help me understand how to write what I’m looking for it would be much appreciated. If you have a different approach to solving the issue I would also love to hear it. as long as you could help me then enact your solution, haha!

Anyways, thanks to anybody who replies.

1 Answer 1

Have a look at the worksheet events available within the Excel namespace. For this, you would use the Change event

If you double click on the worksheet you want to monitor, you can insert a Worksheet_Change sub. Then you can use the intersect function to check if the changed cell was within your range you want to monitor (e.g. D:D).

You can specify which cells you want to change. Here I just gave an example based on what you asked. This will put the output of your function into cell B[R] and put the current date into cell C[R]. Note that I’m using the Now() function since there is no Today() function in VBA. Since this returns both date and time, I’m using the Format function to get just the date.

Just for fun, let’s go a little further into the object model and first get the Worksheet object to which the target range belongs. This is not 100% necessary — you could just rely on ActiveSheet. Now, you probably don’t need to do this, and it’s mostly just for fun, but it’s also worth noting that if you were programmatically making changes to this sheet, but had not activated this sheet first (so another sheet was active) and you had not turned off EnableEvents you would get some strange results 🙂

Explanation

Worksheet change sub is declared like this. The Worksheet objects have pre-defined method stubs for events. Kind of like an interface, though not listed as an interface in the documentation. If you think of it in that concept, this is your event handshake. See the link I posted above for a list of the worksheet events available.
Private Sub Worksheet_Change(ByVal Target As Range)

In the next lines we are getting the worksheet object to which the object named Target belongs. You can see in the sub declaration that Target is declared as an object of the type Range . If you check out the Worksheet object (linked above) or the Range object documentation you’ll see that the range object is a member of the worksheet object, and the documentation kind of sucks here, but FYI the worksheet object is contained within the Parent property. Now, originally I had my code using the ActiveSheet member of the Application object — but I’ve edited it for the reasons given in my answer above.

I use With Blocks to save typing the same Worksheet reference in multiple places. A With block just lets me access the members of the namespace specified (in this case members of the object TargetSheet ) by typing .SomeMember . The compiler understands that every reference like this refers to whatever is specified in the opening With . statement. I personally like this for readability, but I also recommend it for maintenance (change reference one place vs many). Also having a single reference gives a tiny, insignificant, probably not worth mentioning performance boost over multiple references as well.

Next we check whether or not Target is within the range of cells we want to watch. The If. Then should look familiar enough. For our condition we use the boolean operator Not to check if the result of the intersect function (linked above) Is Nothing. The reason we do this is to check if the return is allocated. If an object is allocated the Not SomeObject Is Nothing condition will evaluate to False . If the object is not allocated (i.e. our Intersect function failed to return anything) then the statement evaluates to True . So, from the Intersect function documentation we know that if our return is allocated, the ranges intersect and the intersecting range object was returned. Thus if we want to know if they intersect, we can just check for the opposite of a failure.

If Not Application.Intersect(Target, .Range(«D:D»)) Is Nothing Then

The next lines then just execute some code on cells within the same row as Target . We use the Cells member of the worksheet object to specify what cells to modify. Per the documentation, the default property for Cells is Item which lets us access a range object through a row and column index like this: .Cells[Row,Column] . So, I simply use the row of our Target object and the column you wanted (column «A» =1, «B»=2, etc. You can see this by changing excel properties to R1C1 reference style if you are interested).

.Cells(Target.Row, 2) = ExtractWindowsUser()

And I think the Format() and Now() functions are pretty well explained in the documentation.

Источник

Return to VBA Code Examples

Worksheet_Change Event

You may want to run a macro when a cell changes. A popular use of this ability is to have custom code validate a cell after a change is made. It’s easy to do this by using the worksheet objects change event.

In the Visual Basic Editor you must first double click the sheet name where the cell changes that activates the macro. This opens the code window for that sheet object. In this case I wanted to run a macro when a cell in Sheet1 changes.

worksheet change event

After opening the code window for the Worksheet you place your code in the Worksheet_Change event. The following example will display a message box if the contents of cell A1 change. First the subroutine fires if any cell changes, then the use of an IF..Then statement will run the code only if cell A1 was the cell that changed based on the If…Then.


Private Sub Worksheet_Change(ByVal Target As Range)



If Target.Address = "$A$1" Then

     MsgBox "This Code Runs When Cell A1 Changes!"

End If



End Sub

You can place your code directly in the Worksheet_Change subroutine or call another macro from there.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!


August 15, 2015/



Chris Newman

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. The IF statement checks to see if the cell(s) that was last changed intersects (or matches) cell G7.

‘Determine if change was made to cell G7
  If Not Intersect(Target, Range(«G7»)) Is Nothing 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 Not Intersect(Target, Range(«G7»)) Is Nothing 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:

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.

If you would like to get a copy of the Excel file I used throughout this article, feel free to directly download the spreadsheet by clicking the download button below.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

Throughout your VBA practices, you would get the need to run macros when a certain range or cell changes. In that case, to run macros when a change is made to a target range, we use the change event. Events in VBA enables us to run the macros when a certain event occurs.

Syntax VBA Range Change Event

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("your_range")) Is Nothing Then
      call your_macro
    End If
End Sub

The Event does not work in modules. You need to write them into objects (worksheet, charts, workbook).

Lat’s have an example to learn how to run a macro when a change is made in a specified range.

Example: Run a VBA Macro When A change is made in range A2:A100

First, we choose the sheet on which the event will occur. Double click on that sheet in VBA editor and copy below code or generic code above and make changes as per your requirement.

In this example, I want to run a macro/VBA code when a change is made in range A2: A100 on sheet 2. To do so, I double click on sheet2 in project explorer. It opens the coding page for that sheet. You can right-click on the sheet and click on the view code to do the same.

I need to use the change event. For that, we use default subroutine Worksheet_Change(ByVal Target As Range). It triggers when a specified change is made. So our code is this:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2:A100")) Is Nothing Then
      Call TestEvent
    End If
End Sub

When you make any changes in range A2:A100 on Sheet2, the subroutine TestEvent will be called, as you can see in the gif above.

The TestEvent is the public subroutine in module2. It simply pops up a message that the Event is working.

Sub TestEvent()
 MsgBox "Event is working!"
End Sub

How does it work?

We have put a condition :

If Not Intersect(Target, Range(«A2:A100»)) Is Nothing Then

Here Intersect(Target, Range(«A2:A100»)) Is Nothing returns True if no change is made in Range A2:A100. We put a Not operator before this statement that reverses the output given by «Intersect(Target, Range(«A2:A100″))». Hence, if no change is made in range A2:A100, the expression returns Falls and the sub TestEvent doesn’t get the call. If you do make a change in any cell in range A2:A100, the expression will return True and the event will occur. And that’s what happening here.

Note: You can put any subroutine in this block. It can be from any module. But it should be a public subroutine. You can set the range to any extent. The whole sheet is the limit.

So yeah guys, this how you can call a subroutine or run a macro/VBA code when a change is made in a specified range. It was a basic event example. This event will trigger only when the change is text-based. By text-based I mean if you write anything in the cells or delete, the event will trigger. If you change the formatting of the cells, it will not trigger. There are other methods to do that.

I hope it was helpful. If you have any queries related to this VBA topic or any other excel related topic, let me know the comments section below. And check out our other related and popular posts mentioned below.

Related Articles:

Run Macro When any Change is Made On Sheet | So to run your macro whenever the sheet updates, we use the Worksheet Events of VBA.

Simplest VBA Code to Highlight Current Row and Column Using | Use this small VBA snippet to highlight the current row and column of the sheet.

The Worksheet Events in Excel VBA | The worksheet event are really useful when you want your macros run when a specified event occurs on the sheet.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need filter your data to count specific value. Countif function is essential to prepare your dashboard.

How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

Понравилась статья? Поделить с друзьями:
  • If numbers between excel and
  • If number error excel
  • If not use in a sentence for each word
  • If not this then that excel
  • If not negative excel