简体   繁体   English

Excel VBA 在更改单元格时剪切或复制并粘贴

[英]Excel VBA Cut or copy and paste on change of cell

I am making an inventory system.What i want is to copy closing stock to opening stock column when date will change and closing stock keep its formula just copy values to opening stock.我正在制作库存系统。我想要的是在日期更改时将期末库存复制到期初库存列,期末库存保持其公式,只需将值复制到期初库存。

Date is in cell "AF1" with today date formula =Today() Closing Stock is in Column AB2:AB75 with formula(Opening Stock - Sale = Closing stock)日期在单元格“AF1”中,今天的日期公式 =Today() 收盘股票在列 AB2:AB75 中,公式(开盘股票 - 销售 = 收盘股票)

Private Sub Worksheet_Change(ByVal Target As Range)

 If Target = Range("AF1") Then
    Range("AB2:AB75").Copy
    Range("AA2:AA75").PasteSpecial
 Else

 End If
 End Sub

when i change date it crash TYPE MISMATCH 13 and This become highlight yellow当我更改日期时,它会崩溃 TYPE MISMATCH 13 并且这变为突出显示黄色

If Target = Range("AF1") Then如果目标 = Range("AF1") 那么

If you are going to change anything within a Worksheet_Change event macro, you need to disable event handling so that the sub does not trigger another event and try to run on top of itself.如果您要更改Worksheet_Change事件宏中的任何内容,您需要禁用事件处理,以便 sub 不会触发另一个事件并尝试在其自身之上运行。

Additionally, Target can be one cell or a large number of cells.此外, Target可以是一个单元格,也可以是大量单元格。 You cannot reliably compare it to a single cell.您无法可靠地将其与单个单元格进行比较。 You can however, reliably compare its Range.Address property to a single cell's Range.Address property .但是,您可以可靠地将其Range.Address 属性与单个单元格的Range.Address 属性进行比较

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = Range("AF1").Address Then
        On Error GoTo bm_Safe_Exit
        Application.EnableEvents = False
        Range("AA2:AA75") = Range("AB2:AB75").Value
    Else
        'something else...?
    End If

bm_Safe_Exit:
    Application.EnableEvents = True
End Sub

Using Application.EnableEvents property tp disable events should only be done with error control rthat always turns it back on in case something goes wrong.使用Application.EnableEvents 属性tp 禁用事件只能通过错误控制来完成,如果出现问题,它总是将其重新打开。

Private Sub Worksheet_Change(ByVal Target As Range)

  If Target.Address = "$AF$1" Then
     ' Avoid copy then paste by assigning the value itself
     Target.Worksheet.Range("AA2:AA75").Value = Target.Worksheet.Range("AB2:AB75").Value

  End If

 End Sub

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

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