excel vba runtime error 1004; i don't have select in the code

前端 未结 1 369
無奈伤痛
無奈伤痛 2021-01-25 17:04

I am trying to copy some inputs to a model and copy back the answers to the first sheet. Below is the code. \"data_sheet\" is the sheet with many inputs and \"Final Model\" give

相关标签:
1条回答
  • 2021-01-25 17:53

    The reason you get the error is because you're trying to define a range on wksDest using Cells from the Active worksheet, which will always fail unless wksDest is active. So this statement:

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

    Actually says this:

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

    And since a range can't be defined on one sheet using cells on a different sheet (without taking other extraordinary measures), to avoid that, you can use With block like so:

    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
    

    Or a more direct approach using Resize method:

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

    Both above approaches avoid the unqualified Cells object which is a likely cause of 1004 error.

    Also, since you're only copying values, you can do simple value assignment instead of copy and pastespecial, like so:

    rngDest2.Value = rngSource2.Value
    
    0 讨论(0)
提交回复
热议问题