在macrosfind某个单词的一行中着色

我想知道是否有办法使用VBA来做下列事情:如果macros在B列中find单词“Total”,那么总的行的inner.color将被着色为蓝色,它适用于B列中的所有“总计”字。注意:我有不同的总计…不仅是“总计”

像这样(即从col A到F着色)

在这里输入图像说明

我试过这个,但它不能正常工作,代码是坏的…

Sub forme_couleur() Dim myRow As Integer myRow = 1 While Not IsEmpty(Cells(myRow, 2)) If Cells(myRow, 2).Find(What:="Total") Is Nothing Then myRow = myRow + 1 Else Cells(myRow, 2).Find(What:="Total").Interior.Color = RGB(174, 240, 194) End If myRow = myRow + 1 Wend End Sub 

考虑:

 Sub ColorMeBlue() Dim i As Long, N As Long, s As String N = Cells(Rows.Count, "B").End(xlUp).Row s = "Total" For i = 1 To N If InStr(1, Cells(i, 2).Value, s) > 0 Then Range("A" & i & ":F" & i).Interior.Color = RGB(174, 240, 194) End If Next i End Sub 

编辑#1:

要按数字使用列来引用范围,请使用:

 Sub ColorMeBlue2() Dim i As Long, N As Long, s As String N = Cells(Rows.Count, "B").End(xlUp).Row s = "Total" Firstcol = 1 LastCol = 6 For i = 1 To N If InStr(1, Cells(i, 2).Value, s) > 0 Then Range(Cells(i, Firstcol), Cells(i, LastCol)).Interior.Color = RGB(174, 240, 194) End If Next i End Sub 

您可以通过条件格式来实现这一点,但是如果您必须使用VBA来实现,请使用如下所示的内容:

 Sub test() For i = 1 To Cells(ActiveSheet.Rows.Count, "B").End(xlUp).Row If InStr(1, Cells(i, 2), "Total") Then With Cells(i, 2).EntireRow.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorLight2 .TintAndShade = 0.399975585192419 .PatternTintAndShade = 0 End With End If Next i End Sub 

另一个概念 :你可以使用AutoFilter方法。 使用这种方法不需要任何For循环,或者任何If ,只要使用Range中的所有通过AutoFilter条件="*Total*"的单元格即可。

 Sub ColorMeBlue_Filter() Dim i As Long, N As Long, s As String Dim FirstCol As Long, LastCol As Long Dim FiltRng As Range N = Cells(Rows.Count, "B").End(xlUp).Row s = "Total" ' (just for my testing) 'FirstCol = 1 'LastCol = 6 Range("A1").AutoFilter Range(Cells(1, FirstCol), Cells(N, LastCol)).AutoFilter Field:=2, Criteria1:="=*Total*", _ Operator:=xlAnd ' set FiltRng to only visible cells (that passed the "Total" filter) Set FiltRng = Range(Cells(2, FirstCol), Cells(N, LastCol)).SpecialCells(xlCellTypeVisible) ' modify interior color of all cells at once (one code line) FiltRng.Interior.Color = RGB(174, 240, 194) End Sub 

您可以使用基于公式的条件格式化,使用COUNTIF(a1:f1,“ 总计 ”)函数> 0

使用Range.Find可以避免:循环遍历每行,并需要获取最后一行。

而不是将Range.Find应用于每一行,只需将其应用于整列,无需检查单元格是否为空(有关其他详细信息,请参见Range.Find方法(Excel) )。

Voici votre coderévisé:

假设你的数据位于`A:F'

 Sub forme_couleur() Const kCriteria As String = "Total" Dim rTrg As Range, s1stFound As String With ThisWorkbook.Sheets("DATA").Columns(2) 'change as required Set rTrg = .Cells.Find(What:=kCriteria, After:=.Cells(1), LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext) If Not (rTrg Is Nothing) Then s1stFound = rTrg.Address Do rTrg.EntireRow.Cells(1).Resize(1, 6).Interior.Color = RGB(224, 240, 248) 'RGB(174, 240, 194) give me a green color - changed as required Set rTrg = .Cells.FindNext(After:=rTrg) Loop Until rTrg.Address = s1stFound End If: End With End Sub