+ Reply to Thread
Results 1 to 3 of 3

using ranges on non-active sheets

Hybrid View

  1. #1
    Registered User
    Join Date
    01-23-2010
    Location
    Hertfordshire, England
    MS-Off Ver
    Excel 2003
    Posts
    4

    using ranges on non-active sheets

    Suppose you want to clear a region of a workbook, whose location is to be determined at run-time.

    The obvious code is:

    Sub clear1(ws as worksheet, i as integer, j as integer, k as integer, l as integer)
    ws.range(cells(i,j),cells(k,l)).clearContents
    End Sub

    This gives error number 1004 (the catch-all with no explanation) if ws is not the active worksheet when clear1 is called.

    The work-round is

    Sub clear2(ws as worksheet, i as integer, j as integer, k as integer, l as integer)
    Dim cell1 as range, cell2 as Range
    Set cell1 = ws.range(cells(i, j))
    Set cell2 = ws.range(cells(j, k))
    ws.range(cell1,cell2)).clearContents
    End Sub

    Sub clear2 always works. Why is it necessary and how does it work?

  2. #2
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,481

    Re: using ranges on non-active sheets

    Just fully qualify the range.

    Sub clear1(ws As Worksheet, i As Integer, j As Integer, k As Integer, l As Integer)
    ws.Range(ws.Cells(i, j), ws.Cells(k, l)).ClearContents
    End Sub
    Note use Long instead of Integer in order to reach the end rows of a worksheet
    Cheers
    Andy
    www.andypope.info

  3. #3
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,481

    Re: using ranges on non-active sheets

    Your post does not comply with Rule 3 of our Forum RULES. Use code tags around code. Posting code without them makes your code hard to read and difficult to be copied for testing. Highlight your code and click the # at the top of your post window. For more information about these and other tags, found here

    Oops forgot to mention....

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

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.6.0 RC 1