在VBA中循环通过列时选择单元格

在VBA中循环通过列时选择单元格,vba,excel,Vba,Excel,我有一个宏,用于格式化多页excel文档。在每个工作表上都有一个数据表,我试图根据标题行(第1行)的内容对列进行颜色编码 我想选择列中的第二个单元格,直到最后一行数据,并设置背景色。我现在有这样的东西: For Each ws In ActiveWorkbook.Worksheets With ws .Activate ' Convert to table If .UsedRange.ListObject Is Nothing Then

我有一个宏,用于格式化多页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
我在
范围(列单元格(2,1))上遇到以下错误。选择
,“对象的方法”“范围”“\u全局”“失败”

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

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

无需进行
选择
来设置背景色。正确声明范围变量,并使用该变量:

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
发生错误的原因是您只向
范围
方法传递了一个参数,该方法是一个单元格,其默认属性是它的
,因此除非
列单元格(2,1)
的值中包含有效的范围地址字符串,否则此操作将始终失败。您可以通过在一个
Select
中向
Range
传递两个参数来避免这种情况:

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

甚至:

 col(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
    ...