我正在编写一个简单的格式化宏来替换Excel中表格的行颜色。
我希望这个宏能够格式化任何大小的表(无论行/列大小)。
例如,当我有一个包含6行4列,4行5列或9行10列等的图表时,我希望宏工作。
这是我到目前为止的代码 - 但是我遇到了运行时错误。
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放在首位,有一个'&'而不是逗号等。
如果我只使用Range(“A1:A”和& lastRow),它将起作用,但仅适用于A列中的数据。 我需要它跨越图表中的所有列。
答案 0 :(得分:1)
如果表格都是从单元格A1开始,请将for语句更改为:
For Each Cell In Range("A1", Cells(lastRow, lastCol)) ''change range accordingly
尽管如此,你的for循环的工作方式是改变每个单元格。它可以进行优化,一次将行着色到最后一列。
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
答案 1 :(得分:0)
试试这个:
session.getServletContext()
答案 2 :(得分:0)
总是很好地在代码模块中包含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