Excel VBA,第一个单元格中的颜色在列列表中包含“ IS”和“ S”

时间:2019-10-06 01:35:36

标签: excel vba

B列有许多包含“ IS”和“ S”的单元格。第一个单元格B4包含“ IS”,而第一个单元格B6包含“ S”,都将用颜色37填充。下面的代码:B4 =“ IS1”对1st if是True并有颜色; B5 =“ IS2”对2nd if是正确的,并且已着色,但只希望第一个包含“ IS”的单元格已着色。请使用以下代码提供帮助。

    Dim selectedCells As Range, cell As Range
        Set selectedCells = Range("B3:B38")

'B4 = "IS1"  
'B5 = "IS2" 
'B6 = "S06"
'B7 = "S07" etc

    Dim iproColoured As Boolean, soloColoured As Boolean
        iproColoured = False
        soloColoured = False

    For Each cell In selectedCells

        If Application.IsNumber(Application.Search("IS", cell)) And iproColoured = False Then
                cell.Interior.ColorIndex = 37
                iproColoured = True                
        End If

        If Application.IsNumber(Application.Search("S", cell)) And soloColoured = False Then
                cell.Interior.ColorIndex = 37
                soloColoured = True
        End If

    Next cell

1 个答案:

答案 0 :(得分:1)

由于“ S”位于“ IS”内部,根据我的评论,您可以更改:

If Application.IsNumber(Application.Search("S", cell)) And soloColoured = False Then 

收件人:

If Application.IsNumber(Application.Search("S", cell)) And Not Application.IsNumber(Application.Search("IS", cell)) And soloColoured = False

并确保您不将“ IS”作为“ S”处理