如何告诉 Excel 按行号突出显示行。例如,假设我想要突出显示第 6、10、150、201 行。谢谢。
7 回答
这是另一个基于 Mote 的.EntireRow.Interior.ColorIndex
这并不限制您输入行号,而是让用户可以灵活地在运行时选择行。
Option Explicit
Sub Sample()
Dim Ret As Range
On Error Resume Next
Set Ret = Application.InputBox("Please select the rows that you would like to color", "Color Rows", Type:=8)
On Error GoTo 0
If Not Ret Is Nothing Then Ret.EntireRow.Interior.ColorIndex = 6
End Sub
跟进
有没有办法编写宏来从列表中读取行号并突出显示行?
是的,有办法。假设单元格 A1 到 A10 中的列表,那么您可以使用此代码
Option Explicit
Sub Sample()
Dim i As Long, sh As Worksheet
On Error GoTo Whoa
Application.ScreenUpdating = False
'~~> Set this to the sheet where the rows need to be colored
Set sh = Sheets("Sheet2")
'~~> Change Sheet1 to the sheet which has the list
With Sheets("Sheet1")
For i = 1 To 10
If Not Len(Trim(.Range("A" & i).Value)) = 0 And _
IsNumeric(.Range("A" & i).Value) Then _
sh.Rows(.Range("A" & i).Value).Interior.ColorIndex = 3 '<~~ Red
Next i
End With
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
作为 Motes 答案的替代方案,您可以使用条件格式。
例如:选择 A1:J500,条件格式 >> 新规则 >> 使用公式...
对于公式,请输入:=OR(ROW()=6, ROW()=10, ROW()=150, ROW()=201)
对于基本的 VBA 代码,您始终可以开始录制宏,执行操作,停止录制,查看生成的代码,然后清理以执行您想要的操作。例如,记录突出显示一行的动作(设置 Interior.Color 的值)为您提供:
Rows("13:13").Select
Range("C13").Activate
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
可以删除选择命令和无关的内部属性,从而为您提供:
Rows("13:13").Interior.Color = 65535
在行中添加多选:
Rows("6:6,10:10,150:150,201:201").Interior.Color = 65535
概括:
- 录制宏
- 查看 Excel 的版本
- 使用/编辑您需要的代码
objWB.Cells(rowNum,201).EntireRow.Interior.ColorIndex = 6
ETC
更新:没有意识到这个日期,但我想我会添加这个,因为它与选择的答案相关。
除了 Siddharth Rout 的回答之外,由于我还没有足够的代表发表评论,您可以使用这两行动态计算工作表中有多少行。 xlCellTypeConstants
可以更改为您需要的另一个 XlCellType 常量,并且始终可以更改范围以适应您的电子表格。
Dim numRows As Integer
numRows = Range("A2", Range("A1048576").End(xlUp)).SpecialCells(xlCellTypeConstants).Cells.Count
对不起,如果它不像其他答案那样简洁或优雅,但它可以完成工作。当我为自己的应用程序编写代码时,我需要遍历我的代码。此外,我只需要突出显示部分行,而不是突出显示整行。
Sub Highlight()
Dim ThisWB As Workbook
Dim ThisWS As Worksheet
Dim rows(0 To 3) As Integer
Dim test As String
Set ThisWB = ActiveWorkbook
Set ThisWS = ThisWB.Sheets("Sheet1")
rows(0) = 6
rows(1) = 10
rows(2) = 150
rows(3) = 201
For i = 0 To 3
test = "A" & rows(i) & ":H" & rows(i)
ThisWS.Range(test).Interior.ColorIndex = 15
Next i
End Sub
您也许可以使用条件格式来实现相同的目的
- 将值列表放在一列中(我使用单独的选项卡并为列表命名)
- 在条件格式下-新规则-“使用公式确定要格式化的单元格”
- 阅读这篇文章http://www.howtogeek.com/howto/45670/how-to-highlight-a-row-in-excel-using-conditional-formatting/
- 该规则在公式中使用 vlookup - =$A2=VLOOKUP($A2,list,1,FALSE)