在VBA中遍历列时选择单元格

时间:2018-08-23 16:51:32

标签: excel vba excel-vba

我有一个宏,用于格式化多页Excel文档。每张纸上都有一个数据表,我正在尝试根据标题行(第1行)的内容对列进行颜色编码。

我想选择列中的第二个单元格,直到数据的最后一行,并设置背景色。我目前有这样的东西:

For Each ws In ActiveWorkbook.Worksheets
    With ws
        .Activate

        ' Convert to table
        If .UsedRange.ListObject Is Nothing Then
            .ListObjects.Add SourceType:=xlSrcRange,
                             Source:=.UsedRange, 
                             xllistobjecthasHeaders:=xlYes, 
                             TableStyleName:="Table Style 1"
        End If

        ' Additional Formatting
        ...

        ' Adjust columns
        For Each col In .UsedRange.Columns
            Header = col.Cells(1, 1)

            ' Additional formatting that works
            ...

            Dim col_color As Variant

            ' Color Code
            If Header = "A" Then
                col_color = xlThemeColorAccent6 ' Orange
            ElseIf Header ="B" Then
                col_color = xlThemeColorLight2 ' Blue
            ElseIf Header = "C" Then
                col_color = xlThemeColorAccent4 ' Purple
            ElseIf Header ="D" Then
                col_color = xlThemeColorAccent3 ' Green
            ElseIf Header = "E" Then
                col_color = xlThemeColorAccent2 ' Red
            End If

            Range(col.Cells(2, 1)).Select ' ERROR HERE
            Range(Selection, Selection.End(xlDown)).Select
            With Selection.Interior
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .ThemeColor = col_color
                .TintAndShade = 0.8
                .PatternTintAndShade = 0
            End With


        Next col

我在Range(col.Cells(2, 1)).Select上遇到以下错误,“对象'_Global'的方法'范围'失败”。

我的问题是如何在循环的当前列迭代中正确选择第二个单元格?

1 个答案:

答案 0 :(得分:3)

  

我想选择列中的第二个单元格,直到数据的最后一行,并设置背景色。

无需设置Selection来设置背景颜色。正确声明一个范围变量,并改用它:

Dim formatRange as Range
Set formatRange = Range(col.Cells(2, 1), col.Cells(2, 1).End(xlDown) )

With formatRange.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .ThemeColor = col_color
    .TintAndShade = 0.8
    .PatternTintAndShade = 0
End With

发生错误是因为您仅向Range方法传递了一个参数,该方法是一个单元格,其默认属性为Value,因此除非col.Cells(2,1)包含作为有效范围 address 字符串的值,这将始终失败。您可以通过在 Range中将两个参数传递到Select来避免这种情况:

Range(col.Cells(2, 1), col.Cells(2, 1).End(xlDown)).Select
With Selection.Interior
    ...

或者:

 col.Cells(2, 1).Select
 Range(Selection, Selection.End(xlDown)).Select
 With Selection.Interior
    ...    

甚至:

 col(2,1).Select
 Range(Selection, Selection.End(xlDown)).Select
 With Selection.Interior
    ...     

但是您不应该做那些事情:

几乎是better to avoid Activate/Select