首页 > 解决方案 > 如何仅复制 Excel 中填写的那些行?

问题描述

我有一个包含 10 行和 7 列的工作表。如果所有列都已填满,那么我在第 8 列中输入“确定”,否则数据不完整“。它工作得非常好,但问题是当我将其他列留空(B、C、D 和 E)时,除了列号 A & B(它们已填充),它仍在打印“OK”但它应该是“Data Incomplete”。

lastrow = sheet1.Range("A" & 
Rows.Count).End(xlUp).Row For rownum = 1 To lastrow

    For colnum = 1 To 7

        If IsEmpty(Cells(rownum, colnum)) Then   '<== To Check for Empty Cells
            Cells(rownum, 8) = "Data Incomplete"     '<== To Enter value if empty cell found
            Cells(rownum, colnum).Interior.ColorIndex = 3
            MsgBox "Please fill the column highlighted by Red"
        
        Else
            Cells(rownum, 8) = "OK"
        End If
    Next colnum
Next rownum

标签: excelvba

解决方案


正如 BigBen 所说......您可以使用公式和条件格式来做到这一点。但是,如果您确实想要一个 VBA 解决方案......重新排列您的逻辑如下。请注意,它不会重置填充颜色......但如果需要,您可以添加它。

    Option Explicit
    
    
    Public Sub CheckEmptyCells()
    
        Dim lastrow As Long
        Dim rownum As Long
        Dim colnum As Long
        Dim EmptyCellFound As Boolean
        
        lastrow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
        For rownum = 1 To lastrow
            EmptyCellFound = False
            For colnum = 1 To 7
                If IsEmpty(Cells(rownum, colnum)) Then   '<== To Check for Empty Cells
                  Cells(rownum, colnum).Interior.ColorIndex = 3
                  EmptyCellFound = True
                  MsgBox "Please fill the column highlighted by Red"
                End If
            Next colnum
                
            If EmptyCellFound Then
                Cells(rownum, 8) = "Data Incomplete"     '<== To Enter value if empty cell found
            Else
                Cells(rownum, 8) = "OK"
            End If
            
        Next rownum

End Sub

推荐阅读