Identifying and highlighting a blank row in Excel VBA

浪尽此生 提交于 2020-01-06 16:11:09

问题


Scenario: Each row would contain 23 columns; 20 would contain user populated data and the last 3 would be autogenerated through vba. While running if the vba code identifies the first 20 columns of any row to be blank cells then the whole row is declared blank and highlighted.

I have been able to write the following code:

 For Each rng In Range("A1:A" & LastRow)
    With rng
    If .Value < 1 Then
        MsgBox "Blank Cell found"
        blnkcnt = 0
    For Each mycl In Range("A" & ActiveCell.Row & ":T" & ActiveCell.Row)
        With mycl
            If .Value < 1 Then
                blnkcnt = blnkcnt + 1
            End If
        End With
    Next mycl


    If blnkcnt = 20 Then
        lCount = lCount + 1
        With .EntireRow.Interior
            .ColorIndex = 6
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
        End With
    End If
End If
End With
Next rng

If lCount > 0 Then
   MsgBox "Data contains blank row(s): " & lCount
End

Else
    MsgBox "No blank Rows"
End If

回答1:


I've used a COUNTBLANK function on the first 20 columns of each row to determine if any blank cells exist.

Dim rng As Range, lCount As Long, LastRow As Long

With ActiveSheet    'set this worksheet properly!
    LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
    For Each rng In .Range("A1:A" & LastRow)
        With rng.Resize(1, 20)
            If Application.CountBlank(.Cells) = 20 Then  'All 20 cells are blank
                lCount = lCount + 1
                .EntireRow.ClearContents
                .EntireRow.Interior.ColorIndex = 6
            End If
        End With
    Next rng
End With

If lCount > 0 Then
    MsgBox "Data contains blank row(s): " & lCount
Else
    MsgBox "No blank Rows"
End If

If all 20 cells are blank then the entire row is made blank and yellow highlighting is applied.

I'm using the COUNTBLANK function as it was not clear on whether you have zero-length strings returned by formulas. COUNTBLANK will count these as blanks.




回答2:


Don't use that. Use CountA to check if there is any data in those 20 columns.

See this (untested)

Dim ws As Worksheet
Dim i As Long

'~~> Change this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
    '~~> Find lastrow and change accordingly
    '~~> For demonstration purpose using a hard coded value
    lastrow = 10

    For i = 1 To lastrow
        '~~> Use CountA to check if there is any data
        If Application.WorksheetFunction.CountA(.Range("A" & i & ":T" & i)) = 0 Then
            MsgBox "Row " & i & " is blank"
            '
            '~~> Rest os your code
            '
        End If
    Next i
End With


来源:https://stackoverflow.com/questions/30568038/identifying-and-highlighting-a-blank-row-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!