识别并突出显示Excel VBA中的空白行

情景:每行将包含23列; 20将包含用户填充数据,最后3个将通过vba自动生成。 在运行时,如果vba代码将任何行的前20列标识为空白单元格,则整行被声明为空白并突出显示。

我已经能够写下面的代码:

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 

我在每行的前20列使用COUNTBLANK函数来确定是否存在空白单元格。

 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 

如果所有的20个单元格都是空白的,那么整行将变为空白,并应用黄色突出显示。

我正在使用COUNTBLANK函数,因为不清楚您是否有由公式返回的零长度string。 COUNTBLANK会将这些数据视为空白。

不要使用它。 使用CountA检查这20列中是否有数据。

看到这个( 未经testing

 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