我很难让此代码在最后一列(T和U)上工作 我该怎么做才能改变这种感觉?
代码:
Private Sub Worksheet_ChangeS(ByVal Target As Range) 'column s, structure
If Intersect(Target, Range("S:S")) Is Nothing Then Exit Sub
Dim foundVal As Range
Set foundVal = Sheets("Dropdown").Range("A:A").Find(Target, LookIn:=xlValues, lookat:=xlWhole)
If Not foundVal Is Nothing Then
Target = foundVal.Offset(0, 1)
End If
End Sub
Private Sub Worksheet_ChangeT(ByVal Target As Range) 'column t, component
If Intersect(Target, Range("T:T")) Is Nothing Then Exit Sub
Dim foundVal As Range
Set foundVal = Sheets("Dropdown").Range("D:D").Find(Target, LookIn:=xlValues, lookat:=xlWhole)
If Not foundVal Is Nothing Then
Target = foundVal.Offset(0, 1)
End If
End Sub
Private Sub Worksheet_ChangeU(ByVal Target As Range) 'column U, parameter
If Intersect(Target, Range("U:U")) Is Nothing Then Exit Sub
Dim foundVal As Range
Set foundVal = Sheets("Dropdown").Range("I:I").Find(Target, LookIn:=xlValues, lookat:=xlWhole)
If Not foundVal Is Nothing Then
Target = foundVal.Offset(0, 1)
End If
End Sub
预先感谢
答案 0 :(得分:2)
只有一个Worksheet_Change事件会在更改单元格时触发。
必须从Private Sub Worksheet_ChangeS(ByVal Target As Range)
事件中“手动”调用 Worksheet_Change
,因为它是用户定义的过程。
您应该删除这三个过程,并使用以下内容:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lCol As Long
Dim foundVal As Range
Application.EnableEvents = False
If Not Intersect(Target, Range("S:U")) Is Nothing Then
If Target.Cells.Count = 1 Then 'Check a single cell is changing.
Select Case Target.Column
Case 19 'col S
lCol = 1
Case 20 'col T
lCol = 4
Case 21 'col U
lCol = 9
End Select
Set foundVal = Worksheets("DropDown").Columns(lCol).Find( _
Target.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not foundVal Is Nothing Then
Target = foundVal.Offset(, 1)
End If
End If
End If
Application.EnableEvents = True
End Sub
尽管查看了范围,然后您尝试使用FIND
,但应该能够从“目标”列偏移并在单个语句(而不是三个)中进行查找。
修改:
我已经更新了代码以包含EnableEvents
。在代码末尾,您更改了Target
的值,这将导致Worksheet_Change
事件再次触发。 EnableEvents
阻止了这种情况的发生。
编辑2:
我已经更新了代码以使用单个FIND
。 Select Case
给出要在FIND
命令中搜索的列。
注意:
如果您的代码由于某种原因而崩溃,则可能需要打开立即窗口(Ctrl+G
)并输入Application.EnableEvents = True
,因为在代码停止时这不会重置-您会注意到所有事件代码停止发射。