VBA在细胞变化上运行宏?

时间:2017-03-20 14:57:15

标签: excel vba

我有以下代码和函数,应该在用户键入/粘贴到单元格时运行。

'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 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

此代码有效,但无法正确启动。一旦用户将值键入/粘贴到单元格中(一旦单元格发生更改),代码就应该运行。

目前,代码无效,除非用户逃离单元格,然后返回点击它。

我在私有工作表选择更改事件下有此代码。我不知道这是不对的?当我尝试将其置于私人工作表更改事件下时,它没有做任何事情。

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

2 个答案:

答案 0 :(得分:2)

您希望在Worksheet_Change事件处理程序下使用此功能。

只有当您观察到用户更改工作表上的物理选择时,Worksheet_SelectionChage事件才会触发。

每当更改时,Change事件都会触发(对此有一些限制)。

答案 1 :(得分:1)

这可以通过检查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