所以我正在 Access 中开发一个报告工具。它查询本地表并创建 Excel 文档(通过 VBA)并生成 Excel 文件。
我使用以下代码为替代代码着色,它工作得很漂亮
For a = 1 To rs.RecordCount
With ExcelSheet
.Cells(a + 1, 1) = a
.Cells(a + 1, 1).EntireRow.Interior.ColorIndex = IIf((a + 1) Mod 2 = 0, 2, 15)
End With
Next
注意我必须执行a + 1
,因为a = 1是标题行,那就是标题行。
注意:.Cells(a + 1, 1) = 1
对行进行编号 (1 , 2, 3, ...)
注意:IIf((a + 1) Mod 2 = 0, 2, 15)
2 和 15 是颜色代码。
现在我的问题是,当有人获取 Excel 报告时,他们可能会删除一行,或者执行排序操作或其他操作,当他们这样做时,会弄乱行。
例如:
1 white row
2 grey row
3 white row
4 grey row
如果我对它们进行排序,我会得到
3 white row
1 white row
2 grey row
4 grey row
这不是我想要的,我希望它保留格式和编号 有人可以在 Access 中使用 VBA 来完成此任务吗?
技术:Office 2007
最佳答案
这可以通过ROW()
函数和一些条件格式来完成。 ROW() 函数返回其所在单元格的当前行,因此每当单元格被删除、移动或排序时,它都会发生变化。只要条件发生变化,条件格式就会重新应用,因此移动或排序行会通知 Excel 相应地更新颜色。代码如下所示:
Dim a As Integer
Dim oneRow As Range
For a = 1 To rs.RecordCount
With ExcelSheet
''// show the row number in the first cell
.Cells(a + 1, 1).Formula = "=ROW()"
''// set formatting to alternate row colors
Set oneRow = .Cells(a + 1, 1).EntireRow
oneRow.FormatConditions.Delete
oneRow.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=MOD(ROW()-1, 2)=0"
oneRow.FormatConditions(1).Interior.ColorIndex = 2
oneRow.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=MOD(ROW()-1,2)=1"
oneRow.FormatConditions(2).Interior.ColorIndex = 15
End With
Next a
关于excel - Excel 中交替行颜色/数字 - VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3239970/