查找范围内的空单元格,然后返回与空单元格在同一行中另一个单元格的内容

时间:2019-04-25 17:40:02

标签: excel vba

我有一个从此处(https://wellsr.com/vba/2016/excel/use-isempty-vba-to-check-if-cell-is-blank/)改编的excel vba代码,该代码确定给定范围内的任何单元格是否为空白。如果存在,则返回一个msgbx;如果不存在,则返回一个不同的msg。

我想知道是否有可能返回(在msgbx中)同一行E列中单元格的内容。这将表明需要解决的是具有空单元格的行。

它查看两列。理想情况下,如果两个单元格在同一行中都为空,则它将只返回E列中该单元格的内容一次。

这是代码,你们可以帮我修改以完成我所要的吗?

Sub IsEmptyRange()
Dim cell As Range
Dim bIsEmpty As Boolean

bIsEmpty = False
For Each cell In Range("G26:H38,G25,G23:H24,G22,G6:H21,G5,G3:H4")
    If IsEmpty(cell) = True Then
    'An empty cell was found. Exit loop
    bIsEmpty = True
        Exit For
    End If
Next cell

If bIsEmpty = True Then
    MsgBox "One or more cells are empty"
Else   
    MsgBox "All cells are filled in"
End If
End Sub

谢谢!

AR

1 个答案:

答案 0 :(得分:0)

编辑。包括评论请求。

Option Explicit

Sub IsEmptyRange()
Dim cell As Range
Dim bIsEmpty As Boolean
Dim emptyCellRow As Long
Dim arrRows() As Long, i As Long
Dim arrValues() As String
Dim emptyRow As Variant, emptyRows As String, emptyValues As String
bIsEmpty = False
i = 0
For Each cell In Range("G26:H38,G25,G23:H24,G22,G6:H21,G5,G3:H4")
    If IsEmpty(cell) = True Then
        'An empty cell was found. Exit loop
        emptyCellRow = cell.Row
        bIsEmpty = True

        ReDim Preserve arrRows(i)
        ReDim Preserve arrValues(i)
        arrRows(i) = emptyCellRow
        arrValues(i) = Cells(emptyCellRow, 5).Value
        i = i + 1
    End If
Next cell

If bIsEmpty = True Then
    For Each emptyRow In arrRows
        emptyRows = emptyRows & " " & emptyRow & " "
    Next emptyRow

    For Each emptyRow In arrValues
        emptyValues = emptyValues & " " & emptyRow & " "
    Next emptyRow
End If

If bIsEmpty = False Then
    MsgBox "All cells are filled in"
Else
    MsgBox "Empty rows: " & emptyRows
    MsgBox "Values in empty rows: " & emptyValues
End If

End Sub