[英]Change the color of x number of cells based on the numeric value from another cell
I have range and i want to highlight my range of cells based value i enter in cell Range("C5"). 我有范围,我想根据我在单元格Range(“ C5”)中输入的值来突出显示我的单元格范围。 If i enter 5 in cell "C5" then 5 cells in my range needs to be changed to yellow color. 如果我在单元格“ C5”中输入5,则需要将我范围内的5个单元格更改为黄色。
Dim MY_RANGE As Range
Dim VALUE1 As Integer
Dim CEL As String
Set MY_RANGE = Range("H8,J8,L8,N8,H10,H10,J10,L10,N10,H12,J12,L12,N12,H14,J14,L14,N14,H16,J16,L16,N16,N16")
VALUE1 = Range("C2")
For Each CEL In MY_RANGE.Cells
If CEL.Value = VALUE1 Then
With CEL
.Italic = False
.Bold = True
.Color = 255
.TintAndShade = 0
End With
End If
Next CEL
Can someone help pls.. 有人可以帮忙吗?
You need to introduce a counter and to count: 您需要引入一个计数器并计数:
Public Sub TestMe()
Dim myRange As Range
Dim myCell As Range
Set myRange = Range("H8,J8,L8,N8,H10,H10,J10,L10,N10,H12,J12,L12,N12,H14,J14,L14,N14")
Dim cnt As Long
Dim times As Long
times = Range("C2")
For Each myCell In myRange
With myCell
.Interior.Color = vbBlue
End With
cnt = cnt + 1
If cnt = times Then Exit Sub
Next myCell
End Sub
The idea is that every time the code loops the counter is increased with 1
, hence cnt = cnt + 1
. 这个想法是,每次代码循环时,计数器都会增加1
,因此cnt = cnt + 1
。 If it loops N exactly Range("C2")
times, it exits. 如果它精确地循环N次Range("C2")
次,则退出。
you can use Areas()
property of Range()
object: 您可以使用Range()
对象的Areas()
属性:
Public Sub ColorCells()
Dim iCell As Long
With Range("H8,J8,L8,N8,H10,J10,L10,N10,H12,J12,L12,N12,H14,J14,L14,N14") ' reference your range
For iCell = 1 To Range("C2").Value ' loop through needed areas
.Areas(iCell).Interior.Color = vbYellow
Next
End With
End Sub
Note: in your MY_RANGE
range there were two "H10" occurrences 注意:在您的MY_RANGE
范围内,出现了两次“ H10”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.