VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

后端 未结 3 1139
暖寄归人
暖寄归人 2020-11-30 14:30

I have an Excel document that copies a template sheet into a new sheet on the first time it runs. Any more sheets that follow this template are appended to the newly created

相关标签:
3条回答
  • 2020-11-30 14:53

    Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

    With Worksheets("Cable Cards")
        .Range(.Cells(RangeStartRow, RangeStartColumn), _
               .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
    

    Similarly, fully qualify all your Cells object.

    0 讨论(0)
  • 2020-11-30 14:53

    Solution #1: Your statement

    .Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
    

    does not refer to a proper Range to act upon. Instead,

    .Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
    

    does (and similarly in some other cases).

    Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

    Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

    There are two checks that you can do to make this quite evident:

    1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

    2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

      Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

      Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

      and see the different outcomes.

    Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

    0 讨论(0)
  • 2020-11-30 15:17

    Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

    0 讨论(0)
提交回复
热议问题