突出显示特定行中使用的单元格

我正在写一个VBA文件,需要做一些奇怪的事情。 如果J列中的单元格包含特定值,则需要突出显示该行(而不是整行,只是行的已用部分)。 我已经想通了,除了我的代码是突出显示整个行,我只想要突出显示该行中使用的单元格。 任何人都可以build议吗? 下面的代码

'Yellow Highlight..........THIS IS HIGHLIGHTING THE WHOLE ROW....WHY!!!!! WHY!!!!!!!!!!! Sheets("EMM").Activate With Sheets("EMM") For Lrow = 1 To ActiveSheet.UsedRange.Rows.Count With .Cells(Lrow, "J") If Not IsError(.Value) Then If .Value = "Desk to adjust" Then .EntireRow.Interior.ColorIndex = 6 End If End If End With Next Lrow End With 

 With Sheets("EMM") For Lrow = 1 To .UsedRange.Rows.Count With .Cells(Lrow, "J") If Not IsError(.Value) Then If .Value = "Desk to adjust" Then Sheets("EMM").UsedRange.Rows(Lrow).Interior.ColorIndex = 6 End If End If End With Next End With 

或使用AutoFilter

 With Sheets("EMM").UsedRange .Parent.AutoFilterMode = False .AutoFilter .AutoFilter Field:=10, Criteria1:="Desk to adjust" .Rows(1).Hidden = True 'Header row .Interior.ColorIndex = 6 .Rows(1).Hidden = False 'Header row .AutoFilter .Cells(1, 1).Activate End With 

最容易避免在行上循环并获取非空白单元格或设置filter的方法是在IF中执行此操作:

 .UsedRange.Rows(lRow).Interior.ColorIndex = 6 .UsedRange.Rows(lRow).SpecialCells(xlCellTypeBlanks).Interior.ColorIndex = 0 

(突出显示该行然后不显示空单元格)

下面是一些注释代码,展示了如何使用Range.AutoFilter方法来实现您正在查找的结果。 不需要循环,因此通常效率更高:

 Sub tgrFilter() Dim ws As Worksheet Dim rngData As Range Dim strMatch As String Set ws = ActiveWorkbook.Sheets("EMM") 'We will be working with sheet "EMM" in activeworkbook Set rngData = ws.Range("J1").CurrentRegion 'Get the region that column J is a part of in order to limit the highlighting (so it doesn't highlight entire row) strMatch = "Desk to adjust" 'This is the string/value we are looking for in column J rngData.Interior.Color = xlNone 'Clear any previous highlighting On Error Resume Next 'If there are no results, it would cause an error 'Work with just column J within rngData With Intersect(rngData, ws.Columns("J")) .AutoFilter 1, strMatch 'Note that the filter is not case sensitive 'Color the matching rows contained in the data (not the entire row) Intersect(rngData, .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow).Interior.ColorIndex = 6 .AutoFilter 'Remove the filter End With If Err.Number <> 0 Then 'Error occurred which means there were no results MsgBox "No matches found in column J for [" & strMatch & "]", , "No results" Err.Clear End If On Error GoTo 0 'Remove the On Error Resume Next condition End Sub 

您可以使用条件格式而不是macros。

select您需要突出显示的单元格,并在菜单栏上转到格式 – >条件格式
在这里输入图像说明

在对话框select条件你需要检查,这个例子检查单元格值是否等于“AA”。 一次最多可添加3个条件
在这里输入图像说明

接下来,当条件为真时,单击格式button以格式化单元格。 在这里输入图像说明

完成后,点击确定closures对话框,您将获得所需的高光。 在这里输入图像说明