我想创建一组列(如数组/向量/列表),并在这些列中循环一个宏。
此宏旨在根据其值为一列中的所有单元格着色。
Sub colour_cells()
Dim rgA As Range
Set rgA = Range("A2", Range("A2").End(xlDown))
Dim testcellA As Range
Dim i As Long
Dim c As Long
c = rgA.Cells.Count
For i = 1 To c
Set testcellA = rgA(i)
Select Case testcellA
Case Is = 0
With testcellA
.Interior.Color = rgB(255, 199, 206)
End With
End Select
Next i
End Sub
我想对此进行调整以应用于列A,C,F,G,N和Z。
如何在不设置多个范围对象和复制宏代码的情况下执行此操作?
答案 0 :(得分:0)
您可以通过定义要着色的列数组来实现。然后使用一个循环遍历各列,并使用另一循环遍历每一列中的行。
Option Explicit
Public Sub ColourSomeCells()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1") 'define the worksheet
Dim ColourColumns As Variant
ColourColumns = Array("A", "C", "F", "G", "N", "Z") 'columns you want to color
Dim LastRowInColumn As Long
Dim iRow As Long
Dim iCol As Variant
For Each iCol In ColourColumns 'loop throug the array of columns
LastRowInColumn = ws.Cells(ws.Rows.Count, iCol).End(xlUp).Row 'find last used row in that column
For iRow = 2 To LastRowInColumn 'loop through all used cells in that column
With ws.Cells(iRow, iCol)
Select Case .Value
Case 0 'make zeros red
.Interior.Color = RGB(255, 199, 206)
Case 10, 11, 12 'make values 10-12 green
.Interior.Color = vbGreen
Case Else
End Select
End With
Next iRow 'next row in that column
Next iCol 'next column
End Sub