使用VBAselect和突出显示Excel行
我如何告诉Excel通过行号来突出显示行。 例如,假设我想突出显示第6,10,150,201行。 谢谢。
这里是另一个基于Mote的.EntireRow.Interior.ColorIndex
这不限制你input行号,但给用户在运行时select行的灵活性。
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
跟进
有没有办法编写macros来读取列表中的行号并突出显示行?
是的,有一种方法。 让我们说单元格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的答案的替代,你可以使用条件格式。
例如:selectA1:J500,条件格式>>新build规则>>使用公式…
对于公式,input: =OR(ROW()=6, ROW()=10, ROW()=150, ROW()=201)
对于基本的VBA代码,您可以随时开始录制macros,执行操作,停止录制,查看生成的代码,然后将其清理干净。 例如,logging突出显示行的行为(设置Interior.Color的值)可以:
Rows("13:13").Select Range("C13").Activate With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 65535 .TintAndShade = 0 .PatternTintAndShade = 0 End With
select命令和外部内部属性可以被删除,给你:
Rows("13:13").Interior.Color = 65535
在行中添加多选:
Rows("6:6,10:10,150:150,201:201").Interior.Color = 65535
概要:
- loggingmacros
- 查看Excel的版本
- 使用/编辑你需要的代码
objWB.Cells(rowNum,201).EntireRow.Interior.ColorIndex = 6
等等
更新:没有意识到这个date,但认为我会添加这个,因为它是与所选的答案有关。
除了Siddharth Rout的回答,由于我还没有足够的代表评论,您可以dynamic地找出工作表中有多less行这两行。 可以将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
您可以使用条件格式来实现相同的function
- 把值列表中的列(我使用一个单独的选项卡,并给列表一个名称)
- 在条件格式下 – 新规则 – “使用公式来确定单元格式”
- 阅读这篇文章http://www.howtogeek.com/howto/45670/how-to-highlight-a-row-in-excel-using-conditional-formatting/
- 该规则在公式中使用vlookup = $ A2 = VLOOKUP($ A2,list,1,FALSE)