2017-08-07 57 views
0

我想为我的excel文件中的其他列着色,excel文件有500列。我想出了一个宏,一次为5列。有没有一种方法可以一次为所有列着色。以下是我的代码。我正在寻找一个代码来为所有列着色,我不必手动执行。在excel中着色多列

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 

回答

0

您可以枚举工作表的Columns集合,然后对于每个列,“列”属性是列索引。检查是否是偶数或奇数,然后设置颜色。

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 
+0

谢谢你的代码完美的作品。但是,有没有办法限制我想要着色的列数?如果我想在每个彩色列之间留下两列,我该怎么办?真的很感谢帮助。 –

+0

当然 - 带'step'的'for'循环在这种情况下更容易。查看上面更新的代码。 – ainwood