Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

excel - Test for Null in IF statement

I got the sub below from: Format cell based on formula value from "JosieP"

I am trying to test for Null cells as the sub fails if it encounters one. If it encounters a null cell I want to add a color to the cell

If IsNull(rCell) Then rCell.Interior.Color = 8 does not work but does not fail either.

if clng(Left(Right(rcell.value, 2), 1)) < 3 Then rcell.Interior.ColorIndex = 10 fails when there is a null cell .

I tried adding Not IsNull(rCell) so I would have if clng(Left(Right(rcell.value, 2), 1)) < 3 And Not IsNull(rCell) Then rcell.Interior.ColorIndex = 10 but this fails as well.

Sub Format()

Dim LastRow As Long
Dim WS As Worksheet
dim rCell as range

Set WS = Sheets("sheet1")

LastRow = WS.range("F" & WS.Rows.Count).End(xlUp).Row

for each rcell in WS.range("F2:F" & LastRow).cells

 If IsNull(rCell) Then rCell.Interior.Color = 8

if clng(Left(Right(rcell.value, 2), 1)) < 3 And Not IsNull(rCell) Then rcell.Interior.ColorIndex = 10

next rcell
End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cell values in Excel never contain the Null value. If the cell is blank, it is Empty.

If IsEmpty(rCell.Value) Then ...

Also, a cell that is blank is different from a cell that contains an empty string (zero-length string). To test for those, you use

If Len(rCell.Value) > 0 Then ...

Note that unlike IsEmpty, this is not protected from a type mismatch error. If your cell happens to contain an error value (e.g. #N/A), you will get a runtime error 13: Type mismatch when trying to check its length. To be extra safe, you may want to check for IsError(rCell.Value) first.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...