简体   繁体   English

将新数据粘贴到工作表中时运行宏

[英]Run a Macro When New Data is Pasted into the Sheet

I'm very new to VBA and trying to figure the below out.我对 VBA 很陌生,并试图弄清楚下面的内容。

I want my sub to run whenever new data is pasted (or the value is changed) in cell A1 in the CB worksheet.我希望我的子程序在 CB 工作表的单元格 A1 中粘贴新数据(或更改值)时运行。

The second code works perfectly when its ran alone.第二个代码在单独运行时完美运行。 However, after inserting the first code to run the macro once A1 is change, I get "Run-time error '91: Object variable or with block variable not set" error message.但是,在 A1 更改后插入第一个代码以运行宏后,我收到“运行时错误 '91:对象变量或块变量未设置”错误消息。 The error is triggered at this code line "SHT.Range("k" & I).Value = U.Offset(-1, 0)"错误在此代码行“SHT.Range("k" & I).Value = U.Offset(-1, 0)”处触发

How can I make the second macro run once something is pasted or change in cell A1 ?在单元格 A1 中粘贴或更改某些内容后,如何使第二个宏运行?

1. 1.

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Target, Range("A1:C" & ThisWorkbook.Worksheets("CB").UsedRange.Rows.Count)) Is Nothing Then
       Call LoopandIfStatement
    End If

End Sub

2. 2.

Sub LoopandIfStatement()

Dim SHT As Worksheet
Dim I As Long
Dim O As Long
Dim U As Range

Set SHT = ThisWorkbook.Worksheets("CB")
MyLr = SHT.Cells(Rows.Count, 1).End(xlUp).Row

For I = 1 To MyLr

    If IsEmpty(SHT.Range("a" & I).Value) = False Then
        Set U = SHT.Range("A" & I)
        SHT.Range("k" & I).Value = SHT.Range("A" & I).Value
    Else
        SHT.Range("k" & I).Value = U.Offset(-1, 0)
    End If

Next I

For O = 2 To MyLr
    If SHT.Range("g" & O).Value = "Closing Balance" Then
        SHT.Range("l" & O).Value = SHT.Range("j" & O).Value
    End If
Next O

End Sub

It's likely that the crash is caused by the Change event being triggered by a change initiated by your second procedure.崩溃很可能是由您的第二个过程启动的更改触发的 Change 事件引起的。 Try suppressing events while that procedure is executed.尝试在执行该过程时抑制事件。

Application.EnableEvents = False
Call LoopAndIfStatement
Application.EnableEvents = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM