Arrays 循环指定的列和行
我想创建一个列选择(如数组/向量/列表)并在这些列中循环宏 此宏用于根据其值为一列中的所有单元格着色Arrays 循环指定的列和行,arrays,excel,vba,loops,range,Arrays,Excel,Vba,Loops,Range,我想创建一个列选择(如数组/向量/列表)并在这些列中循环宏 此宏用于根据其值为一列中的所有单元格着色 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
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列
如何在不设置多个范围对象和复制宏代码的情况下执行此操作?您可以通过定义要着色的列数组来执行此操作。然后使用一个循环遍历列,使用另一个循环遍历每列中的行
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
你知道有一种方法可以根据它的值给细胞着色吗?无需使用VBA,条件格式更易于设置如果VBA仍然是您想要的方式,那么您需要在行的第一个循环周围为列创建第二个循环。是的,我知道条件格式。这个宏是我用来导入数据的另一个宏的一部分。我希望在根据单元格的值导入单元格时有条件地格式化单元格。这就是为什么我尝试使用宏来格式化单元格。是的,我的问题更多的是,我不知道如何设置一个对象让列循环,并将范围对象“rgA”调整到顶部。非常感谢,这正是我需要的。