循环VBA代码以检查突出显示的单元格

时间:2019-11-07 23:36:33

标签: excel vba spreadsheet

我想要一个代码来检查范围A1:A14中的每个单元格,如果该单元格突出显示,则在B列中说是或否。

enter image description here

Sub highlighted()

 Dim rng As Range
 Dim c As Range

    Set rng = ActiveCell

    For Each c In rng

      If c.Interior.Pattern <> xlNone Then

        ActiveCell.Offset(0, 1).Range("A1").Select
        ActiveCell.FormulaR1C1 = "Yes"

    Exit Sub

    End If

  Next c

End Sub

此代码对于单个高亮显示的单元格都能成功运行,如何使它遍历所需范围,并在非高亮显示的单元格中包含“否”?

预先感谢!

2 个答案:

答案 0 :(得分:1)

这就是代码。阅读评论并根据需要进行调整。

Sub highlighted()

    Dim evaluatedRange As Range
    Dim evaluatedCell As Range

    Dim sheetName As String
    Dim rangeAddress As String

    ' Adjust these two parameters
    sheetName = "Sheet1"                         ' Sheet name where the range is located
    rangeAddress = "A1:A14"

    Set evaluatedRange = ThisWorkbook.Worksheets(sheetName).Range(rangeAddress)

    ' This will loop through each cell in the range
    For Each evaluatedCell In evaluatedRange

        ' Evaluates if the cell has a pattern (what ever it is)
        If evaluatedCell.Interior.Pattern <> xlNone Then

            ' Set the value of the cell next to the one evaluated (same row - rowOffset:=0 but next column columnOffset:=1) to Yes
            evaluatedCell.Offset(rowOffset:=0, columnOffset:=1).Value = "Yes"

            ' Exit Sub -> This would exit the whole process, so if you want to evaluate the whole range, just delete this line
        Else

            evaluatedCell.Offset(rowOffset:=0, columnOffset:=1).Value = "No"

        End If

    Next evaluatedCell

    MsgBox "Process finished!" ' -> alert the user...

End Sub

如果这是您需要的,请记住标记答案以帮助他人。

答案 1 :(得分:0)

如果我了解您要做什么,您可以简单地做到:

Sub highlighted()
   Dim rng As Range
   Dim c As Range

   Set rng = Range("A1:A14")
   For Each c In rng
        If c.Interior.Pattern <> xlNone Then 
            c.Range("A1").Offset(0,1).Value = "Yes"
        End If
   Next c
End Sub

有关避免不必要的Select的提示,请参见How to avoid using Select in Excel VBA