突出显示单元格包含名称列表中名称的行

时间:2015-11-25 13:08:13

标签: excel excel-vba vba

我如何突出显示包含一个单元格的行,该单元格包含我可以指定的名称列表中的名称?

我认为这最好由宏来完成,但不知道从哪里开始。

2 个答案:

答案 0 :(得分:2)

将此代码放在模块中

Option Explicit
Public Sub ApplyConditionalFormattingsFromAList()
    '
    ' this code create multiple conditional formattings on current selected cells
    ' using a list of conditions along with its formattings defined in another worksheet.
    ' to use, just select the range and then run this code
    '

    Dim iRng        As Range
    Dim ApplyToRng  As Range
    Dim wsCondition As Worksheet

    ' determine the worksheet that define the conditions and formattings
    ' to do this, create a blank worksheet and name it "Names",
    ' then in the worksheet,
    ' column A of the worksheet should contain the names to highlight, start at [A1]
    ' column B of the worksheet should be filled with the highlight color to apply, working in pair with column A
    Set wsCondition = Worksheets("Names")

    ' i make the Macro to apply to current selection.
    ' i made it this way so that you can reuse this code on different sheets multiple times
    ' anyway, you can change this to apply to a fixed range, which can then be turned into automatic running code.
    ' e.g. Set ApplyToRng = Columns("B")
    Set ApplyToRng = Selection

    ' clear the conditional formattings of current selection. otherwise the list of conditional formatting will keep growing.
    ApplyToRng.FormatConditions.Delete

    ' add the conditions
    For Each iRng In wsCondition.Range([A1].Address, wsCondition.Cells(Rows.Count, 1).End(xlUp))
        ApplyToRng.FormatConditions.Add Type:=xlTextString, String:=iRng.Value, TextOperator:=XlContainsOperator.xlContains
        ApplyToRng.FormatConditions(ApplyToRng.FormatConditions.Count).SetFirstPriority
        ApplyToRng.FormatConditions(1).Interior.Color = iRng.Offset(0, 1).Interior.Color
        ApplyToRng.FormatConditions(1).StopIfTrue = False
    Next iRng
End Sub

工作表“名称”看起来像这样

Preview of the Names sheet

答案 1 :(得分:1)

我会把它写成一个宏。

从第一张纸开始。 查找该工作表上最后使用的列和上次使用的行。 使用这些数字迭代每行中的每个单元格。 对于您迭代的每个单元格,您需要转到列表并遍历列表中的每个项目。比较单元格值和列表值,如果它们相同,则突出显示该行并转到下一行。

我希望有所帮助。