Run VBA macro when condition is met - vba

I'm creating a spreadsheet to train my numerical skills.
Now, I use VBA macros to generate a new problem once the current one has been correctly solved. To do so, I still have to press a button in the worksheet, which costs time and is annoying.
Is there a way that I can execute a macro when a certain condition is met?
for instance:
if A1 = "correct!"
then <run macro>
else <do nothing>
Also, let me know if you're interested in the spreadsheet, I'd be happy to share it with you guys.
best,
Pieter

Add this as code for your Worksheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If (Range("A1") = "correct!") Then
''# do your stuff here
End If
End Sub
Worksheet_Change is called whenever something is changed. As it looks like A1 is calculated, you can not check for Target in that case but check for the value of the cell.

Related

Apply autofilter using macro after worksheet has calculated?

So I've set up this spreadsheet at work - I end up having to do a lot of fiddly Excel tasks, though I barely know any VBA - and I want a table to automatically filter itself after the worksheet has been edited. The problem is that the column which is being filtered is full of formulas, which change in response to edits made by the user, and the filter gets applied before the column has finished calculating, producing erratic results. So really what I want is to apply AutoFilter after the worksheet has been calculated, rather than after it has been edited.
The macro I have been using is:
Private Sub Worksheet_Change(ByVal Target As Range)
With ActiveWorkbook.Worksheets("Library").ListObjects("Library")
.AutoFilter.ApplyFilter
End With
End Sub
Naively changing the activating event to Worksheet_Calculate() doesn't work - it appears to be repeatedly applying the filter over and over again.
I'm sure this is a relatively simple one and I just don't know what it is I need to do. Can you guys advise?
(PS first time posting here - hope I have done everything right!)
Never mind, have solved it myself. For anyone else with the problem, I just set calculation to manual and then replaced my code with:
Private Sub Worksheet_Change(ByVal Target As Range)
Calculate
ActiveWorkbook.Worksheets("Library").ListObjects("Library").AutoFilter.ApplyFilter
End Sub

Run macro when linked cell changes value (Excel VBA)

I am currently trying to obtain historical information about how the backlog is developing.
My Excel file is based on queries from an Access Database which can give me a view of the current situation.
I would like to automatically run a macro every time the week number changes. I am currently using the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Worksheet.Range("D3")) Is Nothing Then
Call KPIupdate
End If
End Sub
The macro that should fire is called KPIupdate
My problem is that the Macro only fires if I click the cell. I would like it to just fire when the number changes. The cell "D3" is linked to another cell with the formula =Weeknum(Today();21)
I hope you can help me
According to the MSDN entry for Worksheet_Change:
This event does not occur when cells change during a recalculation. Use the Calculate event to trap a sheet recalculation.
To use Worksheet_Calculate to trap the change in a cell that is set by a formula looking at another cell, you need to set a variable to hold the value of the 'Target' and then check if it has changed after the Calculate event fires.
Here is a simple example:
Option Explicit
Private strCurrentWeek As String
Private Sub Worksheet_Calculate()
If Me.Range("A1").Value <> strCurrentWeek Then
'the linked cell changed
Debug.Print "Sheet1!A1 was changed"
'call another macro
End If
'update the new current week
strCurrentWeek = Me.Range("A1").Value
End Sub
To test this, just set the formula in A1 to be =B1 and then change the value of B1 and check the output in the Immediate window.
You can adapt this code to call KPIupdate where my Debug.Print... statement is.

Making excel graphs appear/disappear

I want a graph only to appear when a condition is fulfilled. To be more precise: I have a drop down menu that changes the content of a graph. If the menu point "Total revenue" is clicked, I want a second graph to appear. I am new to VBA and this is what I came up with so far:
Sub Iffuntion()
Dim SelectedChart As Range
Dim notVisible As Boolean
If Range("D100").Value = Range("E100").Value Then
ActiveSheet.ChartObjects("Testchart").Visible = True
Else
ActiveSheet.ChartObjects("Testchart").Visible = notVisible
End If
End Sub
It works, but I have to execute the VBA to make the graph appear/disappear and I would like that to happen automatically. Also the condition should eventually be in another worksheet to keep the sheet with the graphs nice and tidy. I read that to achieve this I have toI have to activate the other worksheet. Would you recommend this way or is there a better solution?
Thanks for the help and best regards!
Pete
EDIT: Here is the link to a sample file with the proposed solution of Cor_Blimey, that I couldn't get to work properly. The interconnections in the excel are more complicated than they would have to be, but I wanted to be as accurate ad possible in displaying what is actually happening in my excel. Thanks for taking a look!
https://dl.dropboxusercontent.com/u/18406645/sample.xlsm
Assuming you mean that they change, from a data validation drop down list, the contents of a cell then you can put your code into the Worksheet's Worksheet_Change event. This event is fired when the user changes the content of a cell (or by an external link).
Then test for the cell being the right cell then run your code.
Like:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Intersect(Target, Me.Range("D100"))
If Not rng Is Nothing Then
If rng.Value = Me.Range("E100").Value Then
Me.ChartObjects("Testchart").Visible = True
Else
Me.ChartObjects("Testchart").Visible = False
End If
End If
End Sub

Excel option to calculate values for each cell only once

I have a project whose requirements include a circular reference (just so you know why I'm deliberately putting this in my workbook).
Within the doc, I'd like for each cell in the circle to calculate only once. I know this is possible through the Windows Button > Excel Options > Formulas > Enable Iterative Calculations, but I have no way to enforce that option on everyone who touches the workbook. Is there any way (through VBA, maybe, or cell/sheet options?) to make a cell calculate its value only once?
Sounds like a longshot to me, but I really really appreciate your help :)
Something like this:
Private Sub Workbook_Open()
With Application
.Iteration = True
.MaxIterations = 1 '<-- or whatever the maximum allowable # you want
.MaxChange = 0.001 '<-- modify as necessary, or remove if desired
End With
End Sub
Private Sub Workbook_Close()
Application.Iteration = False
End Sub
Place these in the Workbook module.
This was one of the first answers on Google, which you would've found had you done any searching on your own:
http://www.mrexcel.com/forum/excel-questions/444155-need-macro-enable-iterative-calculation.html

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

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
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
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.