VBA 在单元格更改时运行宏?

问题描述 投票:0回答:3

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

'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

此代码可以工作,但无法正确启动。一旦用户在单元格中键入/粘贴一个值(一旦单元格发生更改),代码就应该运行。

目前,除非用户退出单元格然后返回单击它,否则代码无法工作。

我在私人工作表选择更改事件下有此代码。不知道这样说对不对?当我尝试将其放在私人工作表更改事件下时,它没有执行任何操作。

请有人告诉我哪里出了问题?

excel vba
3个回答
2
投票

您希望将其放在

Worksheet_Change
事件处理程序下。

仅当您观察到用户更改工作表上的物理

选择
时,才会触发 Worksheet_SelectionChage 事件。

只要任何单元格

更改
Change事件就会触发(对此有一些限制)。


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

0
投票

我看到的都是网络上带有消息框的示例,但是如果你想运行一个适当的宏,比如说比消息框更复杂的宏,如果里面有更多的结束if,我该把结束if放在哪里?

是否有更短的方法只是说,如果更改此单元格中的值,则运行该特定宏?

© www.soinside.com 2019 - 2024. All rights reserved.