我必须做很多重复,并且我试图尽可能粗糙地自动化。假设我想做以下事情:
我在WorkSheet模块中创建了以下代码:
Dim OldAddress As String ____________________________________________________________
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If OldAddress = Range("F2").Address Then
Range("F9").Select
ElseIf OldAddress = Range("F9").Address Then
Range("F15").Select
ElseIf OldAddress = Range("F15").Address Then
Range("F21").Select
Else
OldAddress = ActiveCell.Address
End If
End Sub
当我在单元格F2中输入数据并单击Enter时,Cursor跳转到单元格F9,但它似乎卡在那里。
有谁知道我做错了什么?
答案 0 :(得分:1)
我会像那样使用更改事件
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rg As Range
On Error GoTo EH
Set rg = Union(Range("F2"), Range("F9"), Range("F15"), Range("F21"))
If Intersect(Target, rg) Is Nothing Then
Exit Sub
End If
Application.EnableEvents = False
Select Case Target.Address
Case "$F$2"
Range("F9").Select
Case "$F$9"
Range("F15").Select
Case "$F$15"
Range("F21").Select
End Select
EH:
Application.EnableEvents = True
End Sub
答案 1 :(得分:1)
我们可以使用不同的事件:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim F2 As Range, F9 As Range, F15 As Range, F22 As Range
Set F2 = Range("F2")
Set F9 = Range("F9")
Set F15 = Range("F15")
Set F21 = Range("F21")
If Not Intersect(Target, F2) Is Nothing Then
F9.Select
Exit Sub
End If
If Not Intersect(Target, F9) Is Nothing Then
F15.Select
Exit Sub
End If
If Not Intersect(Target, F15) Is Nothing Then
F21.Select
Exit Sub
End If
End Sub