【问题标题】:Find empty cells in range, then return contents of another cell in the same row as empty cell查找范围内的空单元格,然后返回与空单元格在同一行中的另一个单元格的内容
【发布时间】:2019-04-25 17:40:01
【问题描述】:

我有一个改编自此处 (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

谢谢!

增强现实

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    编辑。包括评论请求。

    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
    

    【讨论】:

    • 太快了!这真的很好,谢谢。我注意到它只返回空的第一行的内容。我希望用一个空单元格返回所有行的内容,用逗号或类似的东西分隔。例如:“E 列中的值是:a、b、c”...
    • 检查编辑的代码。如果正确,请批准答案:)
    • 是否可以这样,如果同一行中的两个单元格都是空的,它只会返回 E 列中单元格的内容一次?
    • 再次嗨,对不起,我之前没有测试过,但我现在注意到,当范围内没有单元格为空时,我收到运行时错误 (92) For Loop not initialized。指向这一点: For Each emptyRow In arrRows
    • 已编辑答案 - 添加了一项检查以验证至少一个单元格是否为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多