Excel中的示例数据:
A B C
1 9 5
2 4 y 3
3 1 9
4 66 4
5 5 9
我想要做的是当我在B栏中输入Y
时,我想要" somestuff "执行。
If Active.Cell = Y
会在这里工作,因为当我输入Y
并按回车键时,active.cell
将不会是我刚刚输入的Y
Y
} in。通过B列循环不起作用,因为
一个。列
中将有多个Y
个
湾我需要执行" somestuff "在将{{1}}输入单元格后立即。
您能否建议我应该尝试一下?
答案 0 :(得分:1)
正如siddarth建议的那样,Worksheet_change()就是你要找的。以下是您可以在没有任何泄漏的情况下完成任务的方法。将此代码粘贴到您正在编辑y值的工作表中。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim MyRng As Range
Set MyRng = Range("B:B")
Dim PieRng As Range
'Intersect will ensure your current cell lies on column B
Set PieRng = Intersect(Target, MyRng)
'if conditions to ensure trigger code only one cell edited on Col B and is 'y/Y'.
If Target.Columns.Count = 1 And Target.Rows.Count = 1 Then
If Not PieRng Is Nothing And LCase(Target.Text) = "y" Then
'Do my stuff here when y / Y are entered in Column B of current sheet
MsgBox "You entered " & Target.Value & " in Col B"
End If
End If
End Sub
如果失败,请告诉我们......
答案 1 :(得分:0)
我完成了涉及这个问题的工作。以为我会分享最终产品。以下是VBA的作用:
1)检索地址&输入“y”的单元格旁边的单元格的值
2)在不同的列中找到相同的值并返回其地址
3)使该地址成为活动单元格。
代码如下:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim PostRng As Range
Dim PendRng As Range
Dim rValue As Range
Dim lLoop As Long
Dim rFoundCell As Range
Dim PieRng As Range
Set PostRng = Range("B:B")
Set PendRng = Range("D:D")
'"Intersect" will ensure your current cell lies on correct column.
Set PieRng = Intersect(Target, PostRng)
'This block will return the range & value of the cell one column to the left of the column where "y" or "Y" are entered.
'IF conditions to trigger code.
If Target.Columns.Count = 1 And Target.Rows.Count = 1 Then
If Not PieRng Is Nothing And LCase(Target.Text) = "y" Then
'Do my stuff here when y / Y are entered in Column B of current sheet
Set rValue = Target.Offset(0, -1)
' MsgBox "You entered " & rValue.Value
'This will loop through a different column, to find the value identified above, and return its cell address in the other column.
With PendRng
Set rFoundCell = .Cells(1, 1)
For lLoop = 1 To WorksheetFunction.CountIf(.Cells, rValue.Value)
Set rFoundCell = .Find(What:=rValue.Value, _
After:=rFoundCell, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
' MsgBox "val: " & rValue.Value & " Matching Cell: " & rFoundCell.Address
'This will use the cell address identified above to move the active cell to that address.
'Have to convert the address to row/column to use in Cell.Select.
Cells(Range(rFoundCell.Address).Row, Range(rFoundCell.Address).Column).Select
Next lLoop
End With
End If
End If
End Sub