首页 文章

复制不同工作表中的值并将其粘贴到主文件中

提问于
浏览
0

我想创建一些VBA代码来复制多个工作表中的值并将其粘贴到一个主文件中 .

我有以下步骤:

  • 转到工作表并选择范围
Sheets("V01 DEN HAAG").Select
Range("H7").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
  • 转到主文件/选择最低行,将其偏移一个并粘贴值
Sheets("DATASET").Select
Range("B3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Paste

使用最后一个“ActiveCell.Paste”语句似乎有一个小错误 . 它给了我错误:

Object不支持此属性或方法 .

有什么想法会出错吗?

1 回答

  • 1

    ActiveCell 是类 Excel.Range 的对象,此类没有 Paste 这样的方法 . 您需要使用 PasteSpecial 而不是参数 Paste 设置为 xlPasteAll

    ActiveCell.PasteSpecial xlPasteAll
    

    但是,在复制/粘贴范围时选择范围不是一个好习惯 . 相反,您应该使用 Range 类型的变量 . 下面是如何使用变量执行相同任务的示例:

    Sub x()
        Dim sourceRange As Excel.Range
        Dim destinationRange As Excel.Range
        '----------------------------------------------------------------------------------
    
        'Set the reference to [sourceRange].
        Set sourceRange = Sheets("V01 DEN HAAG").Range("H7", Range("H7").End(xlToRight))
    
        'Find the initial cell.
        Set destinationRange = Sheets("DATASET").Range("B3").End(xlDown).Offset(1, 0)
    
        'Resize [destinationRange] to the same size as [sourceRange].
        With sourceRange
            Set destinationRange = destinationRange.Resize(.Rows.Count, .Columns.Count)
        End With
    
    
        'Actual copying & pasting.
        Call sourceRange.Copy
        Call destinationRange.PasteSpecial(xlPasteAll)
    
    
    End Sub
    

相关问题