简体   繁体   中英

Checking to see if two cells are empty

I'm trying to see if two cells are NOT empty in VBA. I'm using the IsEmpty() but I don't think I'm using them right. This is what I have. It's not working because it will always go into the if statement.

Inside my if , I'm manipulating some cells. I shouldn't manipulate them if I go into the else.(Which does nothing), but they end up changing also.

For i = 2 To rows 
        If ((Not IsEmpty(Cells(i, 4))) And (Not IsEmpty(Cells(i, 5)))) Then
            'Do stuff...
        else
            'Do nothing...
        end if
next i

Is this the best way?

These are all valid

If ((Not IsEmpty(Cells(i, 4))) And (Not IsEmpty(Cells(i, 5)))) Then

If Cells(i, 4) <> "" And Cells(i, 5) <> "" Then

If Len(Cells(i, 4)) And Len(Cells(i, 5)) Then

If Len(Cells(i, 4)) > 0 And Len(Cells(i, 5)) > 0 Then

My personal preference is to use Len(). I think it's a clean look.

Wrapping your code in a with statement will make it easier to compare ranges on different worksheets.

With managerSheet

    For i = 2 To rows 
            If  Len(.Cells(i, 4)) And Len(.Cells(i, 5) Then
                'Do stuff...
            else
                'Do nothing...
            end if
    next i

End With

My problem was not my if statement but rather the scope of my calls. I forgot to include the scope of cells. managerSheet.Cells(i, 4).. etc Thanks for the help

The method I normally go for is to check the cell referenced, to a type. As far as I'm aware, when you reference a cell, the interpreter will return a type which best suits the value, ie 1 returns a Double , "abc" returns a String and so on. When a cell is blank, the type returned is Empty .

I carried out a performance test using the technique mentioned here .

Test 1: Using Len() to compare the cells took 40.9080069854244

dTime = MicroTimer
For i = 1 To 10000
  If Len(Cells(i, 4)) And Len(Cells(i, 5)) Then
    'Do something
  Else
    'Do nothing  
  End If
Next i
dTime = MicroTimer - dTime '40.9080069854244

Test 2: Comparing the cells to the type Empty only took 21.0493610010926

dTime = MicroTimer
For i = 1 To 10000
  If Cells(i, 4) <> Empty And Cells(i, 5) <> Empty Then
    'Do something
  Else
    'Do nothing
  End If
Next i
dTime = MicroTimer - dTime '21.0493610010926

It may not look as clean, but if definitely has a benefit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM