使用VBA复制条件格式的单元格

时间:2012-07-09 06:09:16

标签: excel vba excel-vba conditional-formatting

我正在编写一个脚本,将数据从一个工作簿复制到另一个工作簿。后者被用作一种数据库(不是我的想法)。作为测试,我正在复制~300行数据,其中3列为条件格式,其余为纯文本。复制文本很容易并且接近即时,但格式化更加困难。目前我使用以下代码复制格式化的单元格:

thisSheet.Range("G" & CStr(rRow), "I" & CStr(rRow)).Copy
masterSheet.Range("G" & CStr(mRow), "I" & CStr(mRow)).PasteSpecial (xlPasteAll)

大约300行,这需要大约40秒,这太慢了。我无法复制由多行组成的范围,因为它们没有按顺序粘贴。

我尝试使用以下代码来尝试复制格式。

masterSheet.Range("G" & CStr(mRow), "I" & CStr(mRow)).value = thisSheet.Range("G" & CStr(rRow), "I" & CStr(rRow)).value
masterSheet.Range("G" & CStr(mRow), "I" & CStr(mRow)).Font.Color = thisSheet.Range("G" & CStr(rRow), "I" & CStr(rRow)).Font.Color
masterSheet.Range("G" & CStr(mRow), "I" & CStr(mRow)).Interior.ColorIndex = thisSheet.Range("G" & CStr(rRow), "I" & CStr(rRow)).Interior.ColorIndex
'cell color and font color are the only things i am interested in

此代码在大约3秒内执行,但不会复制条件格式应用的格式。

是否有更有效的方法来复制条件格式应用的单元格和字体颜色?

1 个答案:

答案 0 :(得分:1)

尝试将其添加到代码的开头:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

这就结束了:

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

如果这不能提高你所需的速度,我建议将条件格式硬编码到VBA中。

因此,例如,如果其中一个条件格式设置规则使单元格为红色,则数字超过100.将该检查添加到VBA中,同时复制值并根据其值将目标单元格设置为所需格式。 / p>