View Full Version : VB to test a cell value and change it if Null


RossWindows
07-29-2008, 01:14 PM
First time writing VB in excel.
If I had a range of cells that should never be Null,
How would I write VB to test that and change the cell value back to "0" if the user hits delete on the cell?

i.e. Cells D9 through D28 should never be null, so if the user hit delete on D13 for instance, how would I write VB to change that cell to "0" instead of null?

I'm guessing I should use the AfterUpdate() event of something... but should that be on the workbook or the sheet?
Just point me in the right direction and I could probably figure out the rest.
Thanks!

Brianwarnock
07-29-2008, 02:17 PM
Its the worksheet change event, probably code like

Private Sub Worksheet_Change(ByVal Target As Range)

For Each c In Range("d3:d5")
If IsNull(c.Value) Or c.Value = "" Then
c.Value = 0
End If
Next c

End Sub

Brian

RossWindows
07-29-2008, 03:09 PM
Awesome! works like a charm!

I had no idea it was the change event. I'm so used to Access I guess.

Thank you very much!

RossWindows
07-29-2008, 03:18 PM
And If I wanted it to check one more cell in any column, here's how to do that.

Private Sub Worksheet_Change(ByVal Target As Range)
For Each c In Range(("d4,d9:d28"))
If IsNull(c.Value) Or c.Value = "" Then
c.Value = 0
End If
Next c
End Sub