[英]Making a macro in excel to highlight cells that are bigger than a control cell
I want to make a macro that highlights a specific cel in the row if it is greater than the control value.我想制作一个宏,如果它大于控制值,则突出显示行中的特定 cel。 My excel sheet looks as follows:我的excel表如下所示:
So for product A E2 needs to get a red color.因此对于产品 A,E2 需要获得红色。 Because its bigger than the value in cell K2.因为它大于单元格 K2 中的值。 For product B the cells E and H need to get the color red because they are bigger than K3.对于产品 B,单元格 E 和 H 需要变为红色,因为它们比 K3 大。 Product C wont get any colors.产品 C 不会有任何颜色。 This sheet is only an example.这张表只是一个例子。 In the final sheet there will be more than 700 products, so the amount of rows needs to be adjustable.在最终表格中将有 700 多个产品,因此需要调整行数。
I think I need some kind of loop but have no idea how to set it up.我想我需要某种循环,但不知道如何设置它。
Hope someone can help me with this.希望有人能帮我解决这个问题。
Thanks in advance for your time and effort!预先感谢您的时间和精力!
J Rommers J罗默斯
This is a fairly easy task and you could have easily done it by searching and trying something out.这是一项相当简单的任务,您可以通过搜索和尝试轻松完成。
But here's the code:但这是代码:
Dim sheetName As String
Dim startRow As Integer, startCol As Integer
Dim endRow As Integer, endCol As Integer
Dim row As Integer, col As Integer
sheetName = "Sheet1" 'Your sheetname
With Sheets(sheetName)
startRow = 2 'start row for the loop
startCol = 2 'start column for the loop
endRow = .UsedRange.SpecialCells(xlCellTypeLastCell).row 'Last Used Row
endCol = .UsedRange.SpecialCells(xlCellTypeLastCell).Column 'Last Used Column
For row = startRow To endRow Step 1 'Loop through rows
For col = startCol To endCol - 1 Step 1 'Loop through columns | Leave out the Peak Column
If .Cells(row, col).Value > .Cells(row, endCol).Value Then 'If value of cell is bigger than peak column
.Cells(row, col).Interior.Color = vbRed 'mark cell in red
End If
Next col
Next row
End With
You can also try using "conditional formatting" rules for smaller case scenarios.您还可以尝试对较小的案例场景使用“条件格式”规则。 Select the cell you want the rule to be applied, click "new rule" select "format only cells that contain" and then "cell value greater than K5" for example and select the desired cell formating.选择要应用规则的单元格,单击“新规则”选择“仅格式化包含的单元格”,然后选择“大于 K5 的单元格值”,然后选择所需的单元格格式。 This can be copied to other cells as well and changed per case basis.这也可以复制到其他单元格并根据案例进行更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.