Question

Here's a question on VBA.

I found a fine piece of Event Worksheet_Change code and I cannot understand a few points, below I will submit the whole macro:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$A$1" Then Exit Sub
    If Target.Column <> 1 Or Target.Cells.Count > 1 Then Exit Sub
    If IsEmpty(Target) Then Exit Sub ' diablo wrote this line!
    
    If IsNumeric(Target.Value) = False Then
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True
        MsgBox "You entered a non-numeric value.", vbExclamation, _
            "Please: numbers only in column A!"
        Exit Sub
    End If

    Dim oldVal As Double
    Dim newVal As Double
    newVal = Target.Value
    
    Application.EnableEvents = False
    Application.Undo
    oldVal = Target.Value
    Target.Value = oldVal + newVal
    Application.EnableEvents = True
    
End Sub

Now what really puzzles me is this seemingly simple line of code. It's meaning gets a twist in my mind when we put it in an event driven programming macro:

If IsEmpty(Target) Then Exit Sub

The book writes (and epicly confuses me):

Pressing the Delete key triggers the Change event. You might want to delete a cell’s contents and start entering a new set of numbers in an empty cell, so allow yourself the luxury of exiting the Change event if the Delete key is pressed

--> If I throw this statement out of the macro (or comment it) and I press delete I cannot remove a value by pressing delete as the book says but how this works. For all I know the IsEmpty returns a True Boolean answer when the cell is empty and and False when it's not. Help says (press F1 please while the cursor blinks in IsEmpty):

Returns a Boolean value indicating whether a variable has been initialized.

So if I enter a numeric value (the macro adds numeric values input) the value hasn't been initialized? Why it has been initialized when we press Delete? What exactly in a more specific does he mean initialized?- I may not have a clear view of what help means...

Going further down on the code I can absolutely understand that since it is a Change Event when we enter a numeric value I can perfectly understand that the target is the cell chosen and the value is the number we input but we disable events further on and we are assigning again to the oldVal the target.value I suspect that undo puts back the value beforehand and the older value is there to be assigned to oldVal (if that the case please confirm) But how can we really assign this to --> Target.Value?-it represents only the change that it was made.

After that I can clearly understand the rest of the code. My main beef on the first line of code I mentioned I just cannot get the gist how this functionality is created...

Was it helpful?

Solution

Voted up because you're curious enough to ask. However, there is nothing confusing here. The logic of the macro above is simple.

  • If you're modifying A1, it won't continue firing.
  • If it's not in Column A, or the highlighted range is more than 1 column, it won't continue firing.
  • If the cell you're on, the active cell is empty, then it won't continue firing, allowing you to put in an initial value to the cell.

If all the above weren't satisfied (meaning FALSE), the macro continues running. The next few checks are simple.

  • Okay, so the active cell wasn't empty. But did user input a number? If yes, continue running. Otherwise, delete his input and inform user to only use numbers.
  • If user provided a valid number, do the following:
    • Get user's input, store it as newVal.
    • Undo the input, get the original cell's value and store it as oldVal.
    • Add the two together and put it back into the cell.

Don't confuse yourself with the Delete button. What the author meant was simply this:

Worksheet_Change event tracks almost every single change you do on the sheet. This includes typing in, editing, or deleting values from cells. When you press the Delete button while highlighting a cell, you are causing the macro above to happen.

Now, if the above line is NOT commented out, the macro will eventually get to the third check, which is to check if the target cell is empty. Since you've just deleted the content, of course it's empty. The macro will exit and nothing will happen.

If you comment it out, this check will never happen. When you delete the cell's content, you'll continue running and the macro will undo your job again and again.

The way to check it is simple. See my screenshot below:

enter image description here

Put the same breakpoints as I have on the three lines above. Notice that I have the IsEmpty line commented out. Now enter a value into A2. Try deleting it. You'll see it get deleted but the first red line in the macro will get highlighted. This means it's checking your cell's content now. The IsNumeric check is going to evaluate to TRUE which will not exit your code. Basically, it will continue to the bottom part.

Press F5 to continue running the code.

Now you'll arrive at Application.Undo. Before arriving here, note that newVal is going to store your new value (0). Now, your delete will be undone by the Application.Undo line, and 0 will be added to it. Basically, you're just adding 0 repeatedly to the cell's value.

Do not get yourself confused by the terms or by the help file. They're, well, helpful. But consider first the logic of the code before looking up what each thing does. Isolate the ifs and the thens and the elses. Have a paper handy and prepare to write or draw the logic flow of this by hand. That is much better than reading the help file when you don't know what to look for.

Let us know if this clears up the confusion. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top