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

时间:2017-01-24 22:47:54

标签: excel excel-vba vba

我正在尝试将一些输入复制到模型并将答案复制回第一张表。下面是代码。 " data_sheet"是具有许多输入和"最终模型"给出了输出。它很简单;我正在尝试从中复制数据 " 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

1 个答案:

答案 0 :(得分:1)

您收到错误的原因是您尝试使用 Active 工作表中的wksDestCells上定义范围,除非{{{}} { 1}}有效。所以这句话:

wksDest

实际上是这样说的:

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

由于无法使用不同工作表上的单元格在一张纸上定义范围(不采取其他特殊措施),为避免这种情况,您可以使用Set rngSource2 = wksDest.Range(ActiveSheet.Cells(38, 4), ActiveSheet.Cells(40, 4)) 块,如下所示:

With

使用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) 对象,这可能是造成1004错误的原因。

此外,由于您只是复制值,因此您可以执行简单的值分配,而不是Cellscopy,如下所示:

pastespecial