空无效

时间:2017-03-03 15:40:40

标签: excel-vba vba excel

我正在编写一个程序但它无法正常工作。 我会写一个简单的版本

Dim rng as range
Dim message as integer 
Set rng = Range(cells(1,1), cells (4,1))
If isempty(rng) then
   mess = msgbox ("hello", vbyesno, "hello")
      If mess = 6 then
       Msgbox "hello"
       Else
       Msgbox "bye"
       End if
Else
    Msgbox "haha"
End if

这是该计划, 但是当单元格为空或者单元格中有值时,它会执行else语句,即“haha”,并且无论如何都不执行第一个语句,尽管它可能是真的。 为什么会这样,在编写程序时我可能做错了什么。

3 个答案:

答案 0 :(得分:0)

您可以使用CountA查看特定范围内有多少单元格不为空。

关于MSDN

CountA文档

Option Explicit

Sub checkEmptyRange()

Dim Rng As Range

With Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
    Set Rng = .Range(.Cells(1, 1), .Cells(4, 1))
    If WorksheetFunction.CountA(Rng) > 0 Then
        If MsgBox("hello", vbYesNo, "hello") = vbYes Then
           MsgBox "hello"
        Else
           MsgBox "bye"
        End If
    Else
        MsgBox "haha"
    End If
End With    

End Sub

答案 1 :(得分:0)

IsEmpty不是特定于Excel的函数,可以检测空单元格 它是VB6 / A语言的一部分,它会检查Variant类型的变量是否包含特殊值Empty

在检查单个 Excel单元格的内容时,它恰好起作用,因为单个表达式IsEmpty(cell) is understood as IsEmpty(cell.Value)cell.Value单元格返回单个Variant,其Empty可能具有IsEmpty检测到的特殊值。

在其他情况下,它不起作用:

  • 当您将多单元格范围传递给IsEmpty时,range.Value会返回Variant的数组。数组本身永远不会Empty,即使其所有元素都包含Empty
  • 当您传递Range Nothing变量时,IsEmpty无法检测到它,因为Empty不是Nothing

答案 2 :(得分:-1)

首先,当您使用逻辑运算符If... Then时,您必须将两个参数相互比较。尝试使用If isempty(rng) = true thenIf isempty(rng) = false then(在您的情况下,我认为您可能会使用If isempty(rng) = false then)。 其次,我不认为函数isempty适用于一系列单元格。如果我没有弄错的话,当您使用isempty的一系列单元格时,结果始终为false

尝试使用以下代码更改代码:

Dim rng As Range
Dim message As Integer
Dim checker As Boolean
checker = False
Set rng = Range(Cells(1, 1), Cells(4, 1))
For Each cell In rng
    If cell.Value <> "" Then
        checker = True
    End If
Next cell
If checker = True Then
    mess = MsgBox("hello", vbYesNo, "hello")
    If mess = 6 Then
        MsgBox "hello"
    Else
        MsgBox "bye"
    End If
Else
    MsgBox "haha"
End If
相关问题