检查单元格是否为空

时间:2015-05-19 06:02:21

标签: excel excel-vba excel-2010 vba

我需要知道如何执行以下操作:

如果coulmn A不为空,则同一行中的B列或C列不应为空。我有这个代码

With Sheets(1).Range("A" & Rows.Count).End(xlUp).Offset(1)
    If Range("B1:B50").Value = "" Range("C1:50").Value = ""Or Then
        MsgBox "B or C must have a value"
    End If
End With

现在只有在完全填充范围B1.B50时它才有效。

2 个答案:

答案 0 :(得分:0)

LastRow = Cells.Find("*", SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row
Range("A1").Select
Do Until ActiveCell.Row = LastRow + 1
 If IsEmpty(ActiveCell) = False Then
  If IsEmpty(Cells(ActiveCell.Row, 2)) = True Or IsEmpty(Cells(ActiveCell.Row, 3)) = True Then
   MsgBox "Row " & ActiveCell.Row & " has no value in Column B or C"
  End If
 End If
 ActiveCell.Offset(1, 0).Select
Loop

这可行。它使用一个条目获取最后一个单元格,然后循环遍历每一行,检查B或C中是否有值,当A不为空时

答案 1 :(得分:0)

下面的代码将标记值为"!Err"的单元格,建议使用此消息而不是长消息,因为用户将能够直接在工作表中看到错误的单元格。

Const kErr As String = "!Err"
Dim lRowCnt As Long
Dim lRow As Long
Dim bCellEmpty
Dim b As Byte

bCellEmpty = False
lRowCnt = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
With Sheets(1)
    For lRow = 1 To lRowCnt
        If .Cells(lRow, 1).Value <> Empty Then
            For b = 2 To 3
                With .Cells(lRow, b)
                    If .Value = Empty Then
                        .Value = kErr
                        bCellEmpty = True
End If: End With: Next: End If: Next: End With
If bCellEmpty Then MsgBox "Cells marked with: """ & kErr & """ C must have a value"