working with ranges in excel

diana
3StarLounger
Posts: 279
Joined: 01 Jun 2010, 00:27

working with ranges in excel

Post by diana »

In Word I know how to work with ranges

set range 1 =
set range 2 =

Im starting to develop in excel, and thought I could use the range method.
eg

dim range1 as range
dim range2 as range
dim range3 as range

Range("A1").Select
set range1 = selection

'goto next active selection
Range("F5").Select
Selection.End(xlDown).Select
set range2 = selection

'im now wanting to extend selection my 2 ranges, so the area between range 1 and range 2 is selected

set range3 = ?
how can i do this?

or do ranges work different in excel than word

many thanks

dd

User avatar
mbarron
2StarLounger
Posts: 112
Joined: 25 Jan 2010, 20:19

Re: working with ranges in excel

Post by mbarron »

You can shorten your code by assigning the range directly. You do not need to select the cells before you assign them to the variable.

Set range1 = Range("A1")
Set range2 = Range("F5").End(xlDown)

finally

Set range3 = Range(range1.Address & ":" & range2.Address)
Set range3 = Range(range1, range2)


Edited: simplified the range3 code and fixed range2 code

diana
3StarLounger
Posts: 279
Joined: 01 Jun 2010, 00:27

Re: working with ranges in excel

Post by diana »

thanks mbarron

i ran the code and it errors on line

Set range2 = Range("F5").Selection.End(xlDown)

with a debug error message "Runtime error 438, object doesnt support this property or method"

This is excel 2007

diana

User avatar
HansV
Administrator
Posts: 78592
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: working with ranges in excel

Post by HansV »

As mbarron posted, it should be

Set range2 = Range("F5").End(xlDown)

i.e. do not insert .Selection in between.
Best wishes,
Hans

diana
3StarLounger
Posts: 279
Joined: 01 Jun 2010, 00:27

Re: working with ranges in excel

Post by diana »

yes your both right

my apologies...im having a slow day today :scratch:

many thanks again

diana

diana
3StarLounger
Posts: 279
Joined: 01 Jun 2010, 00:27

Re: working with ranges in excel

Post by diana »

one more quick question...

how do i set range3 as Set Print Area

it errors on the following code...

range3 = ActiveSheet.PageSetup.PrintArea


thanks again

diana

User avatar
HansV
Administrator
Posts: 78592
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: working with ranges in excel

Post by HansV »

In the first place, you want to assign a value to PrintArea, not to range3, so you have it the wrong way round.
In the second place, PrintArea is a string such as "A1:F203", not a Range object, so you must use the address of range3:

ActiveSheet.PageSetup.PrintArea = range3.Address
Best wishes,
Hans

diana
3StarLounger
Posts: 279
Joined: 01 Jun 2010, 00:27

Re: working with ranges in excel

Post by diana »

thanks Hans

im new to excel development

thanks again

diana :clapping: