+ Reply to Thread
Results 1 to 4 of 4
  1. #1
    Registered User
    Join Date
    02-05-2010
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    3

    using cells to define range gives run time error

    I run a macro with the following code:

    Code:
        Dim myArray() As Variant
        myArray = Worksheets("name1").Range("A1:B1").Value
        Worksheets("name2").Range("A1:B1").Value = myArray
    And it works fine, copying the cells from name1 to name2.

    If I replace the code with this:

    Code:
        Dim myarray() As Variant
        myarray = Worksheets("name1").Range(Cells(1, 1), Cells(1, 2)).Value
        Worksheets("name2").Range(Cells(1, 1), Cells(1, 2)).Value = myarray
    I get Run time error 1004: Application defined or object defined error

    Why?

    Many thanks!
    Last edited by dudamel; 02-05-2010 at 01:18 AM.

  2. #2
    Forum Moderator shg's Avatar
    Join Date
    06-21-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2007
    Posts
    25,137

    Re: using cells to define range gives run time error

    Any unqualified range reference in a code module refers to the active sheet:
    Code:
        myarray = Worksheets("name1").Range(Cells(1, 1), Cells(1, 2)).Value
        Worksheets("name2").Range(Cells(1, 1), Cells(1, 2)).Value = myarray
    Since only one (at most) of those sheets can be active at a time, one of those lines will ALWAYS generate an error.
    Microsoft MVP - Excel
    Entia non sunt multiplicanda sine necessitate

  3. #3
    Registered User
    Join Date
    02-05-2010
    Location
    Toronto, Canada
    MS-Off Ver
    Excel 2003
    Posts
    3

    Re: using cells to define range gives run time error

    Thank you!

  4. #4
    Forum Guru mikerickson's Avatar
    Join Date
    03-30-2007
    Location
    Davis CA
    MS-Off Ver
    Excel 2011
    Posts
    2,929

    Re: using cells to define range gives run time error

    You can qualify the cells inside the two argument form of Range

    Code:
    myarray = Range(Sheets("Name1").Cells(1,1), Sheet("Name1").Cells(1,2)).Value
    
    With Sheets("name2")
        Range(.Cells(1,1), .Cells(1,2)).Value = myarray
    End With
    _
    ...How to Cross-post politely...
    ..Wrap code by selecting the code and clicking the # or read this. Thank you.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.2.0