当用户将一个触发器input到单元格中时执行一个子例程

Excel中的示例数据:

ABC 1 9 5 2 4 y 3 3 1 9 4 66 4 5 5 9 

我想要做的是当我在列B中inputY时,我想要执行“ somestuff ”。

  1. 我不认为If Active.Cell = Y会在这里工作,因为当我inputY并按回车时, active.cell不会是我刚进入Y那个。
  2. 循环通过列B将无法正常工作

    一个。 列中将会有多个Y

    湾 inputY后,我需要执行“ somestuff ”。

你可以请build议我应该尝试什么?

正如siddarthbuild议的那样,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 

让我们知道如果它失败…

我完成了我所涉及的这个问题。 以为我会分享最终产品。 这是什么VBA:
1)检索input“y”的单元格旁边的单元格的地址和值。
2)在不同的列中find相同的值并返回其地址。
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