如何防止粘贴到多个列?

时间:2016-03-21 18:13:36

标签: excel vba copy-paste

我对VBA很新,我遇到了以下代码片段的奇怪问题。我的目标是在用户手动将数据粘贴到表中时插入行。用户手动复制表格的一部分(让我们说列A1到C25 - 留下未触动的组合D和E),当手动粘贴到A26时,插入行。这样,表格会扩展以适合数据(因为表格下面有更多内容)。

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

如何防止此粘贴的数据覆盖我插入的行上的其他列(以及继续"永远")

' 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

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

1 个答案:

答案 0 :(得分:1)

给它一个机会。我从剪贴板中删除了数据,但首先将其存储到变量中,以便插入行,然后将数据添加到适当的位置,将其他列留空。

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