循环范围使用variables(行和列)

我正在写一个简单的格式macros来replaceExcel中表格的行颜色。

我希望这个macros能够格式化任何大小的表(不pipe行/列大小)。

例如,当我有一个有6行4列,4行5列或9行10列等的图表时,我想让macros工作。

这是我到目前为止的代码 – 但我得到一个运行时错误。

If ActiveSheet Is Nothing = False Then Set MyWS = ActiveWorkbook.ActiveSheet lastCol = MyWS.UsedRange.Columns.Count + 1 lastRow = MyWS.UsedRange.Rows.Count + 1 For Each Cell In Range(lastRow, lastCol) ''change range accordingly If Cell.Row Mod 2 = 1 Then Cell.Interior.ColorIndex = 15 ''color to preference Else Cell.Interior.ColorIndex = 14 ''color to preference or remove End If Next Cell End If 

我已经尝试了Range的多个版本 – 让var列先出现,用'&'代替逗号等。

如果我只使用范围(“A1:A”和lastRow),它将工作,但只适用于列A中的数据。我需要它横跨图表中的所有列。

如果这些表都是从单元格A1开始的,则将for语句更改为:

 For Each Cell In Range("A1", Cells(lastRow, lastCol)) ''change range accordingly 

尽pipe如此,循环的工作方式是改变每个单元格。 它可以被优化,一次为最后一列上色。

 If ActiveSheet Is Nothing = False Then Set MyWS = ActiveWorkbook.ActiveSheet lastCol = MyWS.UsedRange.Columns.Count + 1 lastRow = MyWS.UsedRange.Rows.Count + 1 Dim i As Integer For i = 1 To lastRow If i Mod 2 = 1 Then Range("A" & i, Cells(i, lastcol)).Interior.ColorIndex = 15 Else Range("A" & i, Cells(i, lastcol)).Interior.ColorIndex = 14 End If Next i End If 

尝试这个:

  Dim r As Range For Each r In MyWs.UsedRange.Rows If r.Row Mod 2 = 1 Then r.Interior.ColorIndex = 15 Else r.Interior.ColorIndex = 14 End If Next r 

总是很好,在你的代码模块中包含Option Explicit。 尝试以下操作:

  Option Explicit Sub test() Dim MyWS As Excel.Worksheet Dim objRow As Excel.Range Dim lastCol As Long Dim lastRow As Long Dim lngRow As Long If ActiveSheet Is Nothing = False Then Set MyWS = ActiveWorkbook.ActiveSheet lastCol = MyWS.UsedRange.Columns.Count + 1 lastRow = MyWS.UsedRange.Rows.Count + 1 For lngRow = 1 To lastRow Set objRow = MyWS.Range(MyWS.Cells(lngRow, 1), MyWS.Cells(lngRow, lastCol)) If lngRow Mod 2 = 1 Then objRow.Interior.ColorIndex = 15 'color to preference Else objRow.Interior.ColorIndex = 14 'color to preference or remove End If Next lngRow End If End Sub