excel vba运行时错误1004; 我没有在代码中select

我正在尝试将某些input复制到模型中,并将答案复制回第一个工作表。 下面是代码。 “data_sheet”是有很多input的表单,“Final Model”给出输出。 它非常简单; 我试图将数据从“data_sheet”复制到“最终模型”,然后将答案复制回来。 当我尝试将答案复制回“data_sheet”时,出现错误1004。 只有第一部分是行之有效的。

Private Sub CommandButton1_Click() Dim wksSource As Worksheet, wksDest As Worksheet Dim rngStart As Range, rngSource As Range, rngDest As Range Dim rngStart2 As Range, rngSource2 As Range, rngDest2 As Range For i = 1 To 6 Set wksSource = ActiveWorkbook.Sheets("data_sheet") Set wksDest = ActiveWorkbook.Sheets("Final Model") Set rngSource = wksSource.Range(Cells(5, 3 + i - 1), Cells(23, 3 + i - 1)) 'Paste Data Values Set rngDest = wksDest.Range("C14") rngSource.Copy rngDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'Till this code works. Now i just trying to reverse copy Set rngSource2 = wksDest.Range(Cells(38, 4), Cells(40, 4)) Set rngDest2 = wksSource.Range(Cells(29, 3 + i - 1), Cells(31, 3 + i - 1)) rngSource2.Copy rngDest2.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False Next i 

你得到这个错误的原因是因为你试图使用Active工作表中的Cells来定义wksDest上的一个范围,除非wksDest处于活动状态,否则wksDest总是失败。 所以这个声明:

 Set rngSource2 = wksDest.Range(Cells(38, 4), Cells(40, 4)) 

其实这样说:

 Set rngSource2 = wksDest.Range(ActiveSheet.Cells(38, 4), ActiveSheet.Cells(40, 4)) 

而且,由于不能在一张纸上使用不同纸张上的单元格来定义范围(不采取其他非常措施),为了避免这种情况,可以使用如下的块:

 With wksDest Set rngSource2 = .Range(.Cells(38, 4), .Cells(40, 4)) End With With wksSource Set rngDest2 = .Range(.Cells(29, 3 + i - 1), .Cells(31, 3 + i - 1)) End With 

或者使用Resize方法更直接的方法:

 Set rngSource2 = wksDest.Cells(38,4).Resize(3) Set rngDest2 = wksSource.Cells(29, 3 + i - 1).Resize(3) 

以上两种方法都避免了不合格的Cells对象,这可能是1004错误的原因。

另外,由于您只是复制值,所以您可以执行简单的值赋值而不是copypastespecial ,如下所示:

 rngDest2.Value = rngSource2.Value