尝试生成Excel VBA事件,一旦在某个范围中输入值,该事件就会激发。
所以A列到AS列的范围。如果我在A2列输入一个值,它会将背景色索引更新到范围(A2:AS2(。
下面的代码正在为所有行和列激发。
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Value <> "" Then
currentRow = Target.Row
ActiveSheet.Range("A" & curRow & ":AS" & curRow).Interior.ColorIndex = 15
'Target.Interior.ColorIndex = 15
End If
End Sub
使用intersect检查Target
范围是否在您想要的范围内,例如列A
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Not Intersect(Target, Columns("A")) Is Nothing Then
If Target.Value <> "" Then
curRow = Target.Row
Target.Parent.Range("A" & curRow & ":AS" & curRow).Interior.ColorIndex = 15
'Target.Interior.ColorIndex = 15
End If
End If
End Sub
避免使用ActiveSheet
,而应使用Target.Parent
。ActiveSheet可以是不同的工作表,不一定是目标所在的工作表。
或者使用Target.Resize
:
Target.Resize(ColumnSize:=45).Interior.ColorIndex = 15
所以你最终得到了:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Not Intersect(Target, Columns("A")) Is Nothing Then
If Target.Value <> "" Then
Target.Resize(ColumnSize:=45).Interior.ColorIndex = 15
End If
End If
End Sub