[英]Highlight cell conditional on another cell being clicked
I have VBA code that works, but does not seem to be optimal. 我有可以工作的VBA代码,但似乎不是最佳选择。 The code should change the colour of the text in the relevant cell in columns H & I when a cell in Column N is clicked.
当单击N列中的单元格时,代码应更改H和I列中相关单元格中文本的颜色。
For example, when cell N5 is clicked, the text in cells H5 and I5 should turn white. 例如,当单击单元格N5时,单元格H5和I5中的文本应变为白色。 When it is unclicked, they return to their normal colour.
取消单击后,它们将恢复为正常颜色。
The code does not seem to be optimal because the change in column I lags behind that in column H. 该代码似乎不是最佳的,因为I列中的更改滞后于H列中的更改。
I would like a way to make both change instantaneously. 我想要一种同时更改两者的方法。
(Bonus points if you can make the cells change colour AND turn into bold instaneously, with the constraint that like for colour, the bold disappears once the cell is unselected). (如果您可以使单元格改变颜色并立即变为粗体,则奖励点,与颜色一样,一旦取消选择单元格,粗体就会消失)。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim r As Range
Intersect(Columns("H"), ActiveSheet.UsedRange).Font.Color = vbBlack
Set r = Intersect(Range("N:N"), Target)
If r Is Nothing Then Exit Sub
Cells(r.Row, "H").Font.Color = vbWhite
Intersect(Columns("I"), ActiveSheet.UsedRange).Font.Color = vbBlack
Set r = Intersect(Range("N:N"), Target)
If r Is Nothing Then Exit Sub
Cells(r.Row, "I").Font.Color = vbWhite
End Sub
Please note, this is my first time writing VBA, hence any amateurismes. 请注意,这是我第一次编写VBA,因此是业余爱好者。
You don't need to address each column separately... 您不需要分别解决每一列...
EDIT: added bold and multiple cells 编辑:添加了粗体和多个单元格
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim r As Range, c As Range
Set r = Intersect(Me.Range("N:N"), Target)
'? what to do if user selects multiple cells ?
'E.g. - exit if user has >100 cells selected (possibly whole column)
If r Is Nothing Or Target.Cells.CountLarge > 100 Then Exit Sub
Application.ScreenUpdating = False
HighlightIt Application.Intersect(Me.Range("H:I"), Me.UsedRange), False
For Each c In r.Cells
HighlightIt Me.Cells(c.Row, "H").Resize(1, 2)
Next c
Application.ScreenUpdating = False
End Sub
'utility sub for highlighting/unhighlighting
Sub HighlightIt(rng As Range, Optional hilite As Boolean = True)
With rng
.Font.Color = IIf(hilite, vbWhite, vbBlack)
.Font.Bold = hilite
End With
End Sub
Always worth thinking about what should happen if the user selects multiple cells (or even a whole column). 始终值得考虑的是,如果用户选择多个单元格(甚至整个列),将会发生什么。 Handling this robustly is sometimes a challenge, depending on what you want to happen when they do that.
稳健地处理此问题有时会是一个挑战,这取决于您在执行此操作时想要发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.