为什么 PasteSpecial 方法有时会抛出错误 1004?

Why does PasteSpecial method sometimes throw error 1004?

我想将几个工作表的数据复制到一个工作表中,并从 table 复制除第一行以外的所有内容。

PasteSpecial 有时会因

而失败

Error 1004 "pastespecial method of range class failed"

我可以点击“调试”然后重新开始,代码继续复制。当我在整个过程中多次这样做时,我就结束了。

我尝试了其他粘贴模式,例如 .paste 并添加了 .activate.select 语句。

知道为什么会出现这种行为以及如何解决它吗?

Option Explicit

Sub RunOnAllFilesInFolder()

    Dim folderName As String, eApp As Excel.Application, fileName As String
    Dim wb As Workbook, ws As Worksheet, currWs As Worksheet, currWb As Workbook
    Dim sht As Worksheet
    Dim fDialog As Object: Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
    Dim LastRowWb As Integer, LastRow As Integer
    Dim eof As Integer
    
    Set currWb = ActiveWorkbook: Set currWs = ActiveSheet
    
    Set ws = ThisWorkbook.Worksheets("Artikelliste")
    
    fDialog.Title = "Select a folder"
    fDialog.InitialFileName = currWb.Path
    If fDialog.Show = -1 Then
        folderName = fDialog.SelectedItems(1)
    End If
    
    Set eApp = New Excel.Application:  eApp.Visible = False
    
    fileName = Dir(folderName & "\*.*")
    
    LastRow = 2
    
    Do While fileName <> ""
        'Update status bar to indicate progress
        Application.StatusBar = "Processing " & folderName & "\" & fileName
 
        Set wb = eApp.Workbooks.Open(folderName & "\" & fileName)
        Set sht = wb.Worksheets("Tabelle1")
        
        LastRowWb = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
        
        sht.Activate
        sht.Range("A2" & ":" & "AM" & LastRowWb).Copy
        
        ws.Range("A" & LastRow).PasteSpecial Paste:=xlPasteFormats
        ws.Cells(LastRow, 15).Value = fileName

        ThisWorkbook.Save
        LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row + 1

        eApp.CutCopyMode = False
        
        wb.Close SaveChanges:=False 
        Debug.Print "Processed " & folderName & "\" & fileName
        fileName = Dir()
    Loop
    
    eApp.Quit
    Set eApp = Nothing
    Application.DisplayAlerts = True
    
    Application.StatusBar = ""
    MsgBox "Completed executing macro on all workbooks"
    
End Sub

Any idea why this strange behavior occurs and how it even could be fixed?

  1. Excel 有清除剪贴板的奇怪习惯,因此建议在复制和粘贴操作之间不要做任何其他事情

  2. 您需要 Excel 时间将数据放入剪贴板。特别是当您尝试在循环中执行复制粘贴操作时。

试试这个

sht.Range("A2:AM" & LastRowWb).Copy
DoEvents
ws.Range("A" & LastRow).PasteSpecial Paste:=xlPasteFormats

附带说明,您可能还想阅读 如何避免在 Excel VBA 中使用 Select