excel - 如何防止粘贴到多列中?

标签 excel vba copy-paste

我对 VBA 很陌生,并且在以下代码片段中遇到了一个奇怪的问题。我的目标是当用户将数据手动粘贴到表中时插入行。用户手动复制表的一部分(假设列 A1 到 C25——保持列 D 和 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

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

最佳答案

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

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

关于excel - 如何防止粘贴到多列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36138639/

相关文章:

EXCEL VBA - 遍历列中的单元格,如果不为空,则将单元格值打印到另一列

vba - 将偶尔使用引号的 .CSV 文件导入 MS Access

java - 如何在 SWT 中监听粘贴键盘快捷键

excel - 如何对同一行中不同列中具有相同文本值的列部分进行求和

Excel VBA 错误 : Definitions of property procedures for the same property are inconsistent

python - 将数据从 Excel 工作表 (openpyxl) 传输到数据库表 (dbf)

excel - VBA 在 ListFillRange ActiveX ComboBox 中存储字符串而不是范围

sql - 使用 VBA 处理 Access 数据库内的外部 Access 数据库?

c# - 复制粘贴 UIElement (FrameworkElement)

Android 复制/粘贴菜单立即关闭