显示空的单元格

时间:2018-02-02 19:27:52

标签: excel vba

我使用IsEmpty()来确定单元格中是否有值,并在让文件打印之前显示单元格缺少数据的消息。我希望能够通过显示一条消息来指定哪些单元格缺失,该消息指出哪些单元格没有数据,并且在所有字段都有值之前不让文件打印。

此外,是否可以在工作表中显示该单元格的已定义名称,而不是显示没有值的单元格地址? I.e C2 is NameF2 is Date ....

Private Sub Workbook_BeforePrint(Cancel As Boolean)
    If IsEmpty([C2]) Or IsEmpty([F2]) Or IsEmpty([K2]) Or IsEmpty([N2]) _
    Or IsEmpty([C3]) Or IsEmpty([A8]) Or IsEmpty([F8]) _
    Or IsEmpty([C34]) Or IsEmpty([C35]) _
    Or IsEmpty([C36]) Or IsEmpty([C37]) Or IsEmpty([G35]) _
    Or IsEmpty([G36]) Or IsEmpty([G37]) Or IsEmpty([I35]) _
    Or IsEmpty([I36] Or IsEmpty([I37]) _
    Or IsEmpty([L11]) Or IsEmpty([L18]) Or IsEmpty([L25]) _
    Or IsEmpty([J28]) Or IsEmpty([N28]) Then
        Cancel = True
        MsgBox ("Missing Cell. Please verify form!")
    End If
End Sub

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情......

Private Sub Workbook_BeforePrint(Cancel As Boolean)
Dim rng As Range, cell As Range
Dim EmptyFound As Boolean
Dim str As String
Set rng = Range("C2:C3,F2,K2,N2,A8,F8,L11,L18,L25,J28,N28,C34:C37,G35:G37,I35:I37")
str = "The following cells are empty. Please verify form!" & vbNewLine & vbNewLine
For Each cell In rng
    If IsEmpty(cell) Then
        EmptyFound = True
        str = str & cell.Address(0, 0) & vbNewLine
    End If
Next cell
If EmptyFound Then
    Cancel = True
    MsgBox str, vbExclamation, "Empty Cells Found!"
End If
End Sub

答案 1 :(得分:0)

另一种观点:

Private Sub Workbook_BeforePrint(Cancel As Boolean)
Dim arr
arr = Array("C2", "F2", "K2", "N2", "C3", "A8", "F8", "C34:C37", "G35:G37", "I35:I37")

With Worksheets("Sheet1") ' Change to your sheet.
    Dim rng As Range
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        If rng Is Nothing Then
            Set rng = .Range(arr(i))
        Else
            Set rng = Union(rng, .Range(arr(i)))
        End If
    Next i
    Dim rng2 As Range
    Set rng2 = .Range("A2:I37").SpecialCells(xlCellTypeBlanks)
    Dim oRange As Range
    Set oRange = Intersect(rng, rng2)
    If Not oRange Is Nothing Then
        MsgBox ("Missing Cell. Please verify form!") & vbNewLine & oRange.Address
        Cancel = True
    End If
End If
End Sub