我正在尝试制作一个可以使用的万无一失的工具。
实施例;当有人编辑单元格H2时(即使他们没有更改它,只要他们开始编辑阶段),我希望单元格H3立即将其样式更改为Bad(红色)。编辑H30也是如此;改变H31,H58改变H59,H86改变H87。
这是通过VBA还是条件格式化完成的?
答案 0 :(得分:1)
只测试Worksheet_Change
事件的变化。把这样的东西放在适当的工作表代码模块中:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim addr As String
addr = Target.Address
Select Case addr
Case "$H$2", "$H$30", "$H$58", "$H$86"
Target.Offset(1).Style = "Bad"
End Select
End Sub
答案 1 :(得分:0)
你也可以使用:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("H2, H30, H58, H$86")) Is Nothing Then Target.Offset(1).Style = "Bad"
End Sub
此外,您可能希望在用户通过应用“警报”样式进入任何禁止单元时立即发出警告,并在未经修改的情况下将其删除
在这种情况下,您可以尝试以下代码:
Option Explicit
Const forbiddenRngAddr As String = "H2, H30, H58, H$86"
Dim oldRng As Range
Dim oldValue As Variant
Dim oldStyle As String
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range(forbiddenRngAddr)) Is Nothing Then Target.Offset(1).style = "Bad"
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not oldRng Is Nothing Then
If Not Intersect(oldRng, Range(forbiddenRngAddr)) Is Nothing Then
If oldValue = oldRng.Value Then oldRng.Offset(1).style = oldStyle
End If
End If
With Target
If Not Intersect(.Cells, Range(forbiddenRngAddr)) Is Nothing Then
oldStyle = .Offset(1).style
.Offset(1).style = "Alert"
End If
Set oldRng = .Cells
oldValue = .Value
End With
End Sub
最后,如果您在漫游细胞之后设法处理任何用户修改,则需要更清晰的代码
在这里,我使用注释存储不正确更改的单元格旧值和样式,以便检索并检查后续用户输入
Option Explicit
Const forbiddenRngAddr As String = "H2, H30, H58, H$86"
Dim oldRng As Range
Dim oldValue As Variant
Dim oldStyle As String
Private Sub Worksheet_Change(ByVal Target As Range)
With Target
If Not Intersect(.Cells, Range(forbiddenRngAddr)) Is Nothing Then
If .Comment Is Nothing Then
.Offset(1).style = "Bad"
With .AddComment
.Visible = False
.Text oldValue & "|" & Target.style
End With
Else
If .Text = Split(.Comment.Text, "|")(0) Then
.Offset(1).style = Split(.Comment.Text, "|")(1)
.Comment.Delete
Else
.Offset(1).style = "Bad"
End If
End If
End If
End With
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not oldRng Is Nothing Then
If Not Intersect(oldRng, Range(forbiddenRngAddr)) Is Nothing Then
If oldValue = oldRng.Value Then oldRng.Offset(1).style = oldStyle
End If
End If
With Target
If Not Intersect(.Cells, Range(forbiddenRngAddr)) Is Nothing Then
oldStyle = .Offset(1).style
.Offset(1).style = "Alert"
End If
Set oldRng = .Cells
oldValue = .Value
End With
End Sub