views:

153

answers:

1

Hello all,

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

+4  A: 

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.

Peter Lang
Will also want to test that the value of Target is "correct!"?
PreludeAndFugue
@PreludeAndFugue: Sure, that's what I meant by `do your stuff` :)
Peter Lang
Prelude: thanks for your suggestion. Haven't tried it yet, but Peter Lang is right: I'd like the code to only be executed when the value in the cell is "correct!". The target cell is blank when I do not enter an answer, "correct!" when I enter the correct answer and "wrong!" when the answer is, you guess it, wrong. do your stuff should then contain another if.. function? Pieter
Pieter
<do your stuff> ideally should be another Sub that contains all VBA code needed to reset the sheet and generate another set of problems, maybe even including a MsgBox () asking the user to confirm/cancelIf your <do your stuff> really is a MACRO (Excel4Macro) which I don't believe, then the Run statement would have to be used.
MikeD
Thanks for your comments - I edited my answer. As `A1` is calculated, checking for `Target` was wrong anyway, since changing any cell could result in a change of `A1`.
Peter Lang
Peter, it worked. Thanks!
Pieter