【问题标题】:How do I paste special from multiple workbooks to a master workbook如何将多个工作簿中的特殊内容粘贴到主工作簿
【发布时间】:2016-05-12 11:38:50
【问题描述】:

我正在尝试将文件夹中所有文件的值粘贴到主文件夹,但在粘贴过程中不断出现错误。这是我的代码:

    Sub LoopThrough()
Dim MyFile As String
    Dim erow
    Dim FilePath As String
    Dim DestWB As Workbook
    Dim SourceWB As Workbook


    Set DestWB = ThisWorkbook


    FilePath = "C:\data\"
    MyFile = Dir(FilePath)


    Do While Len(MyFile) > 0
    If MyFile = "Master.xlsm" Then
    Exit Sub
    End If


    Set SourceWB = Workbooks.Open(FilePath & MyFile)
    Workbooks.Open (FilePath & MyFile)
    Range("A1:L51").Copy
    DestWB.Range(Cells(erow, 1), Cells(erow, 12)).PasteSpecial xlValues
    SourceWB.Close False
    MyFile = Dir
    Loop


    End Sub

我能得到一些帮助吗?

【问题讨论】:

    标签: vba excel loops paste


    【解决方案1】:

    这一行

    DestWB.Range(Cells(erow, 1), Cells(erow, 12)).PasteSpecial xlValues
    

    应该是

    DestWB.Sheets("Target Sheet").Range(DestWB.Sheets("Target Sheet").Cells(erow, 1), DestWB.Sheets("Target Sheet").Cells(erow, 12)).PasteSpecial xlValues
    

    可以改写为

    With DestWB.Sheets("Target Sheet")
        .Range(.Cells(erow, 1), .Cells(erow, 12)).PasteSpecial xlValues
    End With
    

    关键是当您不引用ActiveSheet 时,您需要使用工作表和可能的工作簿对象来限定所有Range()Cells() 方法

    另请注意,我使用了"Target Sheet",但这应该更改为您实际要粘贴到的工作表的名称。

    【讨论】:

    • 感谢您的回答。不幸的是,我现在在该行上收到错误 1004。你知道那可能是什么吗?
    • 该消息是瑞典语,但类似错误 1004:程序或对象定义错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多