Home » excel » vba – Call a function when only a specific Excel cell changes on Formula Recalculation

vba – Call a function when only a specific Excel cell changes on Formula Recalculation

Posted by: admin April 23, 2020 Leave a comment

Questions:

As far as i know, Worksheet_Calculate is called when the value of any cell in a worksheet changes on Formula recalculation.

Is there a way so that i need a function to be called only when a specific cell changes on Formula Recalculation

How to&Answers:

Let me see if I interpret your question correctly. You want to know if it is possible to only kickoff a macro if a particular cell (or group of cells) is changed.

The answer is Yes. To tweak Ed’s code a little.

Private Sub Worksheet_Change(byval target as range)

    If Not Intersect(target.address, Range("YourCells")) is Nothing Then 
       MyMacro()
    End If

End Sub

I think your use of “function” is throwing people off. That’s why Ed’s answer is so elaborate.

Ok. It is possible that you stated your question correctly and you just want to gain efficiency. In that case, Ed’s answer solves your immediate problem, but will cause the spreadsheet NOT to calculate automatically when you change other cells.

Answer:

To make something happen when a specific cell is changed, you need to embed the relevant selection change event within the file Worksheet_Change(byval target as Range). We can re-calculate a worksheet when your cell changes as follows:

Private Sub Worksheet_Change(byval target as range)

    If target.address = Range("YourCell").Address Then Application.Calculate

End Sub

Now what you want to do is switch off calculations the rest of the time. If you only want to switch off calculations on the single sheet (and not your whole file), you will need to turn calculations off when it is activated, and on when deactivated e.g.

Private Sub Worksheet_Activate

Application.Calculation = xlCalculationManual

End Sub

Private Sub Worksheet_Deactivate

Application.Calculation = xlCalculationAutomatic

End Sub

Of course, your requirements to re-calculate may be considerably more complex than the example above. Firstly, you may open the file whilst on the sheet in question in which case you should use the Workbook_Open event to detect your sheet, and set calculations accordingly

Then you may have several cells that may require some sort of calculation. Presumably the reason you want to switch off calculations is that the file is running too slowly. If so, and you are identifying all the input cells, you could enter the outputs using code. One method would be to enter the formulas using this guide to entering formulas in Excel Visual Basic. You could then replace the formula with the calculated value e.g. Range("YourCell") = Range("YourCell").Value…so stopping the number of formulas in the sheet constantly growing