簡體   English   中英

VBA在單元格更改上運行宏?

[英]VBA run macro on cell change?

我有以下代碼和功能,它們應在用戶鍵入/粘貼到單元格中時運行。

'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

該代碼有效,但是無法正確啟動。 一旦用戶在單元格中鍵入/粘貼一個值(單元格發生更改),代碼就應該運行。

目前,除非用戶轉義該單元格然后再單擊它,否則該代碼將無法正常工作。

我在私人工作表選擇更改事件下有此代碼。 我不知道這是對的嗎? 當我嘗試將其置於私有工作表更改事件下時,它不會執行任何操作。

請有人能告訴我我要去哪里錯嗎?

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

如您所見,僅當用戶更改工作表上的物理選擇時,才會觸發Worksheet_SelectionChage事件。

每當任何單元更改時都會觸發Change事件(對此有一些限制)。

這可以通過檢查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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM