Results 1 to 3 of 3

Thread: Excel VBA - Set and Select a Range Problem

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    May 2004
    Location
    Right here
    Posts
    275

    Excel VBA - Set and Select a Range Problem

    I have the following VBA code:

    Code:
    Sub user_range()
    
        Dim myRange As Range
        Set myRange = Sheets("EventTypes").Range(Cells(5, 5), Cells(10, 10))
        myRange.Select
    
    End Sub
    Which works fine when the worksheet EventTypes is selected. However when I run the macro with any other sheet selected I get the error message "Run-time error '1004': Application-defined or object defined error". The error is due to the Set myRange line.

    Surely it must be possible to define a range whilst not on the worksheet that the range will be on, and then select that range?

    Thanks
    -Rob
    Last edited by TheRobster; Nov 23rd, 2014 at 10:14 AM.
    http://www.sudsolutions.com

  2. #2
    PowerPoster
    Join Date
    Oct 2008
    Location
    Midwest Region, United States
    Posts
    3,574

    Re: Excel VBA - Set and Select a Range Problem

    Specify the workbook which contains that sheet when you set the range.

  3. #3
    PowerPoster
    Join Date
    Oct 2010
    Posts
    2,141

    Re: Excel VBA - Set and Select a Range Problem

    Your issue is due to the use of the unqualified Cells(x,y) references. When you enter an unqualified reference, and it works, it is working because it is defaulting to a referenced on the Application object. With that stated, your code:
    Code:
    Set myRange = Sheets("EventTypes").Range(Cells(5, 5), Cells(10, 10))
    is actually
    Code:
    Set myRange = Application.Sheets("EventTypes").Range(Application.Cells(5, 5), Application.Cells(10, 10))
    However, Application.Cells represents the cells on the Application.ActiveWorkSheet object. So your code is really:
    Code:
    Set myRange = Application.ActiveWorkBook.Sheets("EventTypes").Range(Application.ActiveWorkSheet.Cells(5, 5), Application.ActiveWorkSheet.Cells(10, 10))
    So you are telling it to return a Range from EventTypes that consists of a range from the ActiveSheet. That works when the active sheet is EventTypes, but makes no sense if the active worksheet is not EventTypes.

    You will need construct the cell references to be independent of ActiveWorkSheet.

Posting Permissions

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



Click Here to Expand Forum to Full Width