VBA在单元格更改上运行macros?

我有下面的代码和函数应该在用户input/粘贴到单元格时运行。

'Insert Depot Memo Data for user Dim oCell As Range, targetCell As Range Dim ws2 As Worksheet On Error GoTo Message If Not Intersect(Target, Range("C:C")) Is Nothing Then ' <-- run this code only if a value in column I has changed If Not GetWb("Depot Memo", ws2) Then Exit Sub With ws2 For Each targetCell In Target Set oCell = .Range("J1", .Cells(.Rows.Count, "J").End(xlUp)).Find(what:=targetCell.Value, LookIn:=xlValues, lookat:=xlWhole) If Not oCell Is Nothing Then Application.EnableEvents = False targetCell.Offset(0, 1).Value = oCell.Offset(0, 1) targetCell.Offset(0, 2).Value = oCell.Offset(0, -2) Application.EnableEvents = True End If Next End With End If 

function:

 Function GetWb(wbNameLike As String, ws As Worksheet) As Boolean Dim Wb As Workbook For Each Wb In Workbooks If Wb.Name Like "*" & wbNameLike & "*" Then '<-- check if workbook name contains "Depot Memo" Set ws = Wb.Worksheets(1) Exit For End If Next GetWb = Not ws Is Nothing End Function 

此代码有效,但不能正确启动。 只要用户在单元格中键入/粘贴一个值(一旦单元格发生变化)代码就会运行。

目前,代码不工作,除非用户转义单元,然后回去点击它。

我有私人工作表select更改事件下的此代码。 我不知道这是对的吗? 当我试图把它放在一个私人的工作表更改事件它不会做任何事情。

请有人告诉我我要去哪里错了吗?

这可以通过检查Worksheet_Change来完成。 下面提供的是一个将检查一个范围的单元格的例子。 在这个例子中A1:C10。

 Private Sub Worksheet_Change(ByVal Target As Range) Dim KeyCells As Range ' The variable KeyCells contains the cells that will ' cause an alert when they are changed. Set KeyCells = Range("A1:C10") If Not Application.Intersect(KeyCells, Range(Target.Address)) _ Is Nothing Then ' Display a message when one of the designated cells has been ' changed. ' Place your code here. MsgBox "Cell " & Target.Address & " has changed." End If End Sub 

您需要在Worksheet_Change事件处理程序下执行此操作。

Worksheet_SelectionChage事件仅在用户更改工作表上的物理select时触发。

Change事件触发任何单元格更改 (对此的一些限制)。