我正在測試下面的Worksheet_Event代碼。它正在做一些奇怪的事情。這些基本上是三個部分的代碼:Worksheet_Event:如何查找單元格和偏移量1和2列
#1) Enter "EXPL-" & Target.Value
#2) Find a cell in Column R with this language:
"Out of Standard (Comment Needed)"
Then, move over one column, and highlight cell.
Then, go over 1 more column form there, and highlight cell.
#3) Conditional Format for missing values
好像#1和#3做工精細,但#2不突出柱S或列的T細胞,它從過突出的下一個單元格活動細胞。活動單元格應該是在列R.
Private Sub Worksheet_Change(ByVal Target As Range)
'#1)
If Target.Column <> 1 Then Exit Sub
On Error GoTo ErrHandler
Application.EnableEvents = False
If Target.Column = 1 Then
If IsNumeric(Target.Value) Then
Target.Offset(0, 0).Value = "EXPL-" & Target.Value
End If
End If
ErrHandler:
Application.EnableEvents = True
'#2)
lRow = Range("R" & Rows.Count).End(xlUp).Row
Set MyRows = Range("R19:R" & lRow)
For Each cell In MyRows
On Error Resume Next
If cell.Value = "Out of Standard (Comment Needed)" Then cell.Address.Select
Selection.Offset(0, 1).Select
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.399945066682943
End With
If cell.Value = "Out of Standard (Comment Needed)" Then cell.Address.Select
Selection.Offset(0, 1).Select
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.399945066682943
End With
Next
'#3)
lRow = Range("B" & Rows.Count).End(xlUp).Row
Set MyRows = Range("B19:B" & lRow)
MyRows.Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=ISBLANK(B19)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.399945066682943
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
在Change事件上運行的代碼正在對工作表進行更改,當然這個工作表稱爲更改事件,導致出現「奇怪的事情」。要做的事是在代碼開始運行時禁用事件,並且只有在完成所有更改(Application.EnableEvents = True)後才啓用它們。除此之外,我推薦使用Range對象而不是Selection對象,比如MyRows.Formatconditions.Add,而沒有任何Select操作。 – Variatus