gpt4 book ai didi

excel - 检测到更改时将范围复制到另一个工作表的下一行

转载 作者:行者123 更新时间:2023-12-04 22:28:18 25 4
gpt4 key购买 nike

我正在开发一个 VBA 脚本,该脚本监视某个范围(“A4:Q4”)的变化,因为该范围使用“RTD”功能并每秒左右刷新一次。一旦它检测到该范围中的一个值发生更改,我希望它将该范围复制到新工作表中,然后粘贴到下一个可用行中。

我试图在下面的代码,但目前它所做的只是替换 Sheet2(目标)中的当前行,它不会将其添加到下一个可用行。

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 = Worksheets("Sheet1").Range("A4:Q4")

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."

'find next free cell in destination sheet
Dim NextFreeCell As Range
Set NextFreeCell = ThisWorkbook.Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Offset(1)

'copy & paste. Yes, I also want R4 to copy over
Worksheets("Sheet1").Range("A4:R4").Copy
NextFreeCell.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False


End If

End Sub

实际上,我只想将所有更改的日志记录到 sheet2 中,并在更改发生时将范围复制到下一个可用的空行。将它分配给一个按钮会很好,一次单击将启动记录器,另一次单击将停止它,而不是仅在工作簿打开时自动启动,但现在的方式也可以。

谢谢!!

更新:

我已经尝试改用此代码,但它仍然没有向 Sheet2 添加新行:
    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 = Worksheets("Sheet1").Range("A4:Q4")

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then


Dim NextRow As Range
Set NextRow = Range("A" & Sheets("Sheet2").UsedRange.Rows.Count + 1)
Sheet1.Range("A4:R4").Copy
Sheet2.Activate
NextRow.PasteSpecial Paste:=xlValues, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing

End If

End Sub

它只是在 Sheet2 中没有正确偏移!啊!

最佳答案

您需要将您的 NextRowWith 内声明以确保您获得正确的行数。

Sheet1.Range("A4:R4").Copy

With Sheets("Sheet2")
Dim NextRow As Range
Set NextRow = .Range("A" & .UsedRange.Rows.Count + 1)

NextRow.PasteSpecial Paste:=xlValues, Transpose:=False

Application.CutCopyMode = False
End With

关于excel - 检测到更改时将范围复制到另一个工作表的下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com