检查两个单元格是否为空

我试图看看两个单元格在VBA中是不是空的。 我正在使用IsEmpty()但我不认为我正确使用它们。 这是我的。 它不工作,因为它会一直进入if语句。

在我的内部,我正在操纵一些细胞。 我不应该操纵他们,如果我进入其他(什么都不做),但他们最终也会改变。

 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 

这是最好的方法吗?

这些都是有效的

如果((不IsEmpty(Cells(i,4)))和(Not IsEmpty(Cells(i,5))))Then

如果Cells(i,4)<>“”和Cells(i,5)<>“”那么

如果Len(Cells(i,4))和Len(Cells(i,5))那么

如果Len(Cells(i,4))> 0和Len(Cells(i,5))> 0那么

我个人的偏好是使用Len()。 我认为这是一个干净的外观。

将代码封装在with语句中可以使不同工作表上的范围比较容易。

 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 

我的问题不是我的陈述,而是我的电话范围。 我忘了包括单元格的范围。 managerSheet.Cells(i, 4).. etc谢谢你的帮助

我通常使用的方法是检查引用的单元格。 据我所知,当你引用单元格时,解释器将返回一个最适合该值的types,即1返回一个Double"abc"返回一个String等等。 当单元格为空时,返回的types为Empty

我使用这里提到的技术进行了性能testing。

testing1:使用Len()比较单元格取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 

testing2:比较单元格的typesEmpty只用了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 

它可能看起来不那么干净,但如果肯定有好处。