我如何防止粘贴到多列?

我对VBA很新,而且我遇到了一个奇怪的问题,下面的代码片断。 我的目标是当用户将数据手动粘贴到表中时插入行。 用户手动复制表格的一部分(假设列A1到C25 – 保持graphicsD和E不变),当手动粘贴到A26时,插入行。 这样,表就会展开以适合数据(因为表中有更多的内容)。

现在,下面显示的代码确实工作,我唯一的问题是,在列(A到C)的粘贴数据在所有列(D到F,G到I等)上重复。

如何防止这个粘贴的数据覆盖我插入的行上的其他列(并从“永远”继续)

' When cells are pasted, insert # of rows to paste in Dim lastAction As String ' If a Paste action was the last event in the Undo list lastAction = Application.CommandBars("Standard").Controls("&Undo").List(1) If Left(lastAction, 5) = "Paste" Then ' Get the amount that was pasted (table didn't expand) numOfRows = Selection.Rows.Count ' Undo the paste, but keep what is in the clipboard Application.Undo ' Insert a row ActiveCell.offset(0).EntireRow.Insert End If 

我使用命令栏的撤消控制的原因是因为此代码需要在手动粘贴事件上运行。

给这个一个镜头。 我从剪贴板中删除了数据,但首先将其存储到一个variables中,以便可以插入行,然后将数据添加到适当的位置,而将其他列留空。

 Private Sub Worksheet_Change(ByVal Target As Range) ' If a Paste action was the last event in the Undo list Dim lastAction As String lastAction = Application.CommandBars("Standard").Controls("&Undo").List(1) If Left(lastAction, 5) = "Paste" Then Dim rng() As Variant rng() = Target numofRows = Target.Rows.Count 'get amount of rows pasted numofColumns = Target.Columns.Count 'get amount of columns pasted With Application .EnableEvents = False 'stop events from firing momentarily .Undo 'undo paste action .CutCopyMode = False 'remove data from clipboard End With ActiveCell.Resize(numofRows, 1).EntireRow.Insert 'insert new amount of rows based on paste ActiveCell.Resize(numofRows, numofColumns).Value = rng() 'replace pasted values Application.EnableEvents = True 'turn back on event firing End If End Sub