如果标头不为空,则VBA循环遍历列

时间:2015-05-08 03:24:36

标签: vba loops

如果列标题不为空,我想开始遍历每一列。我不知道如何找到每列的标题,因为它是字母,而不是数字。

我用Google搜索了许多代码,但它们并没有完全按照我的要求进行。

以下是代码。任何帮助将不胜感激。



Sub ColorGradient()

'Find the last roll number
Dim Lastrow As Integer
Lastrow = Range("A:A").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Dim cs As ColorScale
Dim rng As Range

'Loop through each column
For Each rng In Range("B4:AA" & Lastrow).Columns
    'Set color gradient
    Set cs = rng.FormatConditions.AddColorScale(ColorScaleType:=3)

    ' Set the color of the lowest value
        With cs.ColorScaleCriteria(1)
            .Type = xlConditionValueLowestValue
            With .FormatColor
                .Color = RGB(248, 105, 107)
                .TintAndShade = 0
            End With
        End With
       
        ' In the middle
        With cs.ColorScaleCriteria(2)
            .Type = xlConditionValuePercentile
            .Value = 50
            With .FormatColor
                .Color = RGB(255, 244, 189)
                .TintAndShade = 0
            End With
        End With
       
        ' At the highest value
        With cs.ColorScaleCriteria(3)
            .Type = xlConditionValueHighestValue
            With .FormatColor
                .Color = RGB(0, 204, 255)
                .TintAndShade = 0
            End With
        End With
Next rng

End Sub




1 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解,但是首先测试“标题”行值是否为空,然后设置列范围并对其进行处理。

Option Explicit

Sub test()

Dim rHdrs As Range
Dim r As Range
Dim rCol As Range
Dim Lastrow As Integer

With ThisWorkbook.Sheets(1)

    Lastrow = .Columns(1).Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Set rHdrs = .Range("B3:AA3")

    For Each r In rHdrs
        If r.Value <> "" Then

            Set rCol = .Range(.Cells(4, r.Column), .Cells(Lastrow, r.Column))
            'loop through cells in rCol
            'do stuff with the non-empty header column ranges here

        End If
    Next r
End With

End Sub

我以为你是在Thisworkbook.sheets(1)上做的。