突出显示范围内的空白单元格

时间:2020-09-11 19:40:01

标签: excel vba

我正在研究一个宏,该宏可以复制,粘贴然后创建各种尺寸的模板形式。在宏将模板工作表另存为单独的文件之前,我先通过范围(通常通过数据范围的D14:G末尾)进行搜索,然后以自定义颜色突出显示空白单元格。但是,我有一个非常特殊的用例,在该范围内(D14:G16)没有空白单元格,因此它一直在选择低于此范围的所有空白单元格(从A17到工作表末尾)。有人可以帮我解决这个问题吗?下面是突出显示空白单元格的宏摘录:

 Set rLastCell = Sheets("Diversity Form").Cells.find(What:="*", After:=Sheets("Diversity Form").Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
        xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
        'ColumnLetter2 = Split(Cells(1, rLastCell.Column).Address, "$")(1)
        lCol = Sheets("Diversity Form").Cells(Rows.count, 4).End(xlUp).Row
        'Dim ColumnLetter As String
        'color only blank cells
        For h = 4 To 7
        ColumnLetter = Split(Cells(1, h).Address, "$")(1)
        Let item = ColumnLetter & "14:G" & lCol
        Sheets("Diversity Form").Range(item).SpecialCells(xlCellTypeBlanks).Select
        On Error Resume Next
            With Selection.Interior
               .Pattern = xlSolid
               .PatternColorIndex = xlAutomatic
               .ThemeColor = xlThemeColorAccent1
               .TintAndShade = 0.599993896298105
               .PatternTintAndShade = 0
            End With
    
        Next

1 个答案:

答案 0 :(得分:2)

  • 不需要在这里循环,也不需要弄乱列字母,也不必Select
  • 首先使用WorksheetFunction.CountBlank测试是否有空白。
With Sheets("Diversity Form")
    Dim lastRow As Long
    lastRow = .Cells(.Rows.Count, 4).End(xlUp).Row

    Dim checkRange As Range
    Set checkRange = .Range(.Cells(14, 4), .Cells(lastRow, 7)) ' Or .Range("D14:G" & LastRow)
End With

If WorksheetFunction.CountBlank(checkRange) > 0 Then
    With checkRange.SpecialCells(xlCellTypeBlanks).Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.599993896298105
        .PatternTintAndShade = 0
    End With
End If