【问题标题】:Excel VBA loop columns and rows color cell based on valueExcel VBA循环基于值的列和行颜色单元格
【发布时间】:2022-11-17 06:34:31
【问题描述】:

我想遍历 excel 工作表的行和列(范围 B3:I16)。如果单元格值与我的 p 列匹配,我想将单元格的背景着色为相应的十六进制代码(O 列)或 rgb 代码(L:M 列)的颜色。

我在“Next j”行看到一个编译错误,上面写着“Next without for”,我认为这意味着前一行有错误。我无法解决该错误。

一旦我的代码开始工作,是否有更有效的方法来检查 P 列中的所有值而无需大量的 if else 语句?

Sub format_quilt()

Dim i, j As Long

'psuedo code python style
'for i in range column number max
'       for j in range row number max
'                if (cell value == to index name in p4:p14) or (cell directly above == index name in p4:p14)
'                        color current cell using hex number


For i = 3 To Range("R2").Value
    For j = 2 To Range("R1").Value
        If (Cells(i, j).Value = Range("P4").Value) Or (Cells(i - 1, j).Value = Range("P4").Value) Then
        Cells(i, j).Interior.Color = RGB(Range("L4").Value, Range("M4").Value, Range("n4").Value)
    
    
    Next j

Next i


End Sub

【问题讨论】:

  • 在内循环中缺少End If

标签: excel vba for-loop if-statement


【解决方案1】:

您可以使用Match() 来查看您在 Col P 中的列表。

例如(从匹配的单元格中复制填充颜色):

Option Explicit

Sub format_quilt()

    Dim c As Range, ws As Worksheet, m, rngList As Range
    Dim i As Long, j As Long

    Set ws = ActiveSheet 'or some specific sheet
    Set rngList = ws.Range("P4:P14")  'lookup range

    For i = 3 To ws.Range("R2").Value
        For j = 2 To ws.Range("R1").Value
            Set c = ws.Cells(i, j)
            m = Application.Match(c.Value, rngList, 0)
            If Not IsError(m) Then  'got a match?
                c.Interior.Color = rngList.Cells(m).Interior.Color
            Else
                c.Interior.ColorIndex = xlNone 'clear if no match
            End If
        Next j
    Next i
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多