Excel VBA-无法从一个工作表复制到另一个工作表

我正在尝试从不同的工作表复制基于数据填写汇总表。 但是,我得到了这个模糊的错误“应用程序或对象定义错误”,我不知道是什么问题。 代码如下:

Sub jtest() 'For j = 3 To Rows.Count (will loop later once I make sure one iteration works) j = 3 Atext = Cells(j, "A").Text Worksheets(Atext).Range("U6").Copy Destination:=Worksheets("Summary 2").Range(j, "C") Worksheets(Atext).Range("X6").Copy Destination:=Worksheets("Summary 2").Range(j, "D") Worksheets(Atext).Range("Z6").Copy Destination:=Worksheets("Summary 2").Range(j, "F") Worksheets(Atext).Range("V7").Copy Destination:=Worksheets("Summary 2").Range(j, "G") ' Next j End Sub 

首先,我build议在最上面添加Option Explicit ,这样你就不得不声明variables。 其次,粘贴时错误地使用Range() 。 更改为Cells() ,你很好去!

 Sub jtest() Dim j&, Atext$, lastRow& Application.ScreenUpdating = False Application.Calculation = xlCalculationManual lastRow = Worksheets("Sheet1").Cells(Sheet("Sheet1").Rows.Count,1).End(xlUp).Row ' CHANGE THAT WORKSHEET AS NECESSARY. I'm also assuming your Column A has the most data. For j = 3 To lastRow Atext = Worksheets("Sheet1").Cells(j, "A").Text ' CHANGE THAT WORKSHEET AS NECESSARY Worksheets("Summary 2").Cells(j, "C").Value = Worksheets(Atext).Range("U6").Value Worksheets("Summary 2").Cells(j, "D").Value = Worksheets(Atext).Range("X6").Value Worksheets("Summary 2").Cells(j, "F").Value = Worksheets(Atext).Range("Z6").Value Worksheets("Summary 2").Cells(j, "G").Value = Worksheets(Atext).Range("V7").Value Next j Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub 

我已经编辑了你的想法。 假设你的“Sheet1”列有最多的数据(根据需要编辑),我创build了一个lastRowvariables,而不是循环200,000次(这会发生在使用Rows.Count时)。 我也刚刚设置范围的值相等,这将跳过使用剪贴板,有点快。 请注意,如果您需要格式,则这将只保留这些值,然后切换回.Copy Destination:= ...但将Range(j, "C")更改为Cells(j, "C")

而不是以这种方式引用单元格,请创build引用该单元格的范围对象。 使用上面的答案给出的例子:

 dim row as range, summaryRow as range, sh as worksheet set sh = activeworkbook.sheets("Summary 2") for each row in sh.usedrange.rows 'I prefer to use "usedrange" 

在循环遍历行或列时,您将执行此操作,请将您正在使用的行设置为行范围,对于汇总行也是如此,然后将一行复制到另一行。

 row.cells(column).copy summaryRow