在Excel中着色多个列

时间:2017-08-07 00:37:11

标签: excel-vba vba excel

我正在尝试为excel文件中的每个其他列着色,excel文件有500列。我想出了一个宏,它一次着色5列。有没有办法可以一次为所有列着色。这是我的代码。我正在寻找一个颜色所有列的代码,我不必手动完成。

 Sub Macro2()
'
' Macro2 Macro
'

'
ActiveCell.Range("A1:A2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlUp)).Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Range("A1:A19").Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1:A19").Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1:A19").Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1:A19").Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
End Sub

1 个答案:

答案 0 :(得分:0)

您可以枚举工作表的Columns集合,然后对每个列枚举'列' property是Column Index。检查它是否是偶数或奇数,并设置颜色。

Public Sub Colour()
Dim Column As Range
For Each Column In ActiveSheet.Columns
    If Column.Column Mod 2 = 0 Then
        Column.Interior.Color = vbRed
    End If
Next Column
End Sub

要限制列,或更改订购的数量,您可以使用" for"循环而不是For Each循环。例如:

Public Sub Colour()
Dim colIndex As Long
For colIndex = 1 To ActiveSheet.Columns.Count Step 3    '//Step 3 means every third column.
    ActiveSheet.Columns(colIndex).Interior.Color = vbRed
Next colIndex
End Sub

如果您想将其限制为500列:

Public Sub Colour()
Dim colIndex As Long
For colIndex = 1 To 500 Step 3    '//Step 3 means every third column.
    ActiveSheet.Columns(colIndex).Interior.Color = vbRed
Next colIndex
End Sub