首页 > 解决方案 > 尝试复制和粘贴时看到错误 104

问题描述

我在将内容从 Shout 工作簿复制和粘贴到 MontlyRepTool 工作簿时遇到问题 - 看到运行时 1004 错误,最后一部分突出显示。我已经尝试了每种复制和粘贴方法,但不断看到出现相同的错误。请参阅下面的代码:

Sub CopyDailyShout2M()

Dim LastRow As Long
Dim LastColumn As Long

Dim wb As Workbook
Dim DailyShout As String
Dim MonthRep As String
Dim Dataset As Workbook
Dim MonthlyRepTool As Workbook
Dim shout As Workbook

    myFile = "Dataset"
    otherFile = "Monthly Reporting Tool"
    shoutFile = "Copy of Daily Shout"

    For Each wb In Application.Workbooks
        If wb.Name Like myFile & "*" Then
           Set Dataset = Workbooks(wb.Name)
        End If
    Next wb
    
    For Each wb In Application.Workbooks
        If wb.Name Like otherFile & "*" Then
           Set MonthlyRepTool = Workbooks(wb.Name)
        End If
    Next wb
    
    For Each wb In Application.Workbooks
        If wb.Name Like shoutFile & "*" Then
           Set shout = Workbooks(wb.Name)
        End If
    Next wb
    
    'Counting last row and last column of the Daily Shout File (for copy and paste purposes)
    LastRow = shout.Worksheets(1).Cells(Rows.Count, "A").End(xlUp).Row
    LastColumn = shout.Worksheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
    
shout.Worksheets(1).Range(shout.Worksheets(1).Cells(1, 1), shout.Worksheets(1).Cells(LastRow, LastColumn)).Copy _
MonthlyRepTool.Worksheets("Sheet3").Range(MonthlyRepTool.Worksheets("Sheet3").Cells(1, 1))

        
        
End Sub

标签: excelvba

解决方案


在指定源范围时,您的第一个错误(现已更正)是一个问题。您的新问题在于您的目标范围:MonthlyRepTool.Worksheets("Sheet3").Range(MonthlyRepTool.Worksheets("Sheet3").Cells(1, 1))将不起作用。Range可以使用一个或两个参数调用 - 方法。如果使用一个参数调用,这必须是一个指定范围的字符串,例如“A1”。仅当使用两个参数调用时,您才指定定义开始和结束单元格的两个单元格(请参阅https://docs.microsoft.com/de-de/office/vba/api/excel.worksheet.range)。
由于单元格也是范围,因此您可以简单地写MonthlyRepTool.Worksheets("Sheet3").Cells(1, 1)为目的地(或使用MonthlyRepTool.Worksheets("Sheet3").Range("A1"),任何最适合的。)

当你有这样的陈述时,真的很难看到错误。将这些陈述分解成更小的部分总是一个好主意。

将源和目标范围定义为变量

Dim sourceRange as Range, destRange as Range
With shout.Worksheets(1)
     Set sourceRange = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn))
End With
Set destRange = MonthlyRepTool.Worksheets("Sheet3").Cells(1, 1)
sourceRange.Copy destRange 

您的第一个代码(在编辑之前)将是

Set sourceRange = shout.Worksheets(1).Range(Cells(1, 1), Cells(LastRow, LastColumn))

并在此阶段已经抛出运行时错误 - 向您表明源范围定义存在问题(不是 dest 范围,不是Copy-method)。
相似地,

Set destRange = MonthlyRepTool.Worksheets("Sheet3").Range(MonthlyRepTool.Worksheets("Sheet3").Cells(1, 1))

会给您一个运行时错误,告诉您在定义目标范围时遇到问题。


推荐阅读