使用 VBA 在 Excel 中为一系列单元格着色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3335931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:39:57  来源:igfitidea点击:

Coloring a range of cells in Excel using VBA

excel-vbarangecellbackground-colorvba

提问by JTone

I have a spreadsheet that I use at work to keep track of returned contracts. I've set up a color key so I can quickly glance at the sheet to see which contracts still need to be returned to us and which account manager the account belongs to.

我有一个电子表格,我在工作中使用它来跟踪退回的合同。我已经设置了一个颜色键,所以我可以快速浏览一下表格,看看哪些合同仍然需要退还给我们,以及该账户属于哪个客户经理。

The account manager's initials are listed in column A; from there I would like to color the range of cells in that row (A:H) depending on who's initials are entered in A. Right now I have the following code in place, but I don't like the way the spreadsheet looks with the entire row colored:

客户经理的姓名缩写列于 A 列;从那里我想根据在 A 中输入的姓名首字母为该行中的单元格范围着色(A:H)。现在我有以下代码,但我不喜欢电子表格的外观整行颜色:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Column <> 1 Then Exit Sub

Select Case Target

Case "MKH"
Target.EntireRow.Interior.ColorIndex = 36

Case "MAH"
Target.EntireRow.Interior.ColorIndex = 39

Case "MJM"
Target.EntireRow.Interior.ColorIndex = 34

Case "JVE"
Target.EntireRow.Interior.ColorIndex = 35

Case Else
Target.EntireRow.Interior.ColorIndex = 0

End Select

P.S. The majority of workers in our office are still using Office 2003, so conditional formatting is not an option.

PS 我们办公室的大多数员工仍在使用 Office 2003,因此无法选择条件格式。

回答by Tobias

If your question is how to color a part of the row instead of the whole one, this should work:

如果您的问题是如何为行的一部分而不是整个行着色,这应该可行:

Range("A" & Target.Row, "H" & Target.Row).Interior.ColorIndex = 10

回答by Martin Carlsson

Depending of how many rows you have, the speed of your computer, version of excel etc. Events usually slows down your worksheet and to a large degree, slows down other VBA codes.

取决于您拥有的行数、计算机速度、excel 版本等。事件通常会减慢您的工作表速度,并且在很大程度上会减慢其他 VBA 代码的速度。

For what you want to do “Conditional formatting”is always a better alternative.

对于您想做的事情,“条件格式”总是更好的选择。