[英]Excel VBA loop columns and rows color cell based on value
我想遍历 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
您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.