PDA

View Full Version : Solved: Selecting Noncontiguous Cells



Opv
05-31-2011, 02:00 PM
Before I give up on this as a viable VBA option, I wanted to see if there is something I'm missing....

I've worked with non contiguous ranges of cells before but I've always hard coded the ranges into my code. However, if I select non contiguous cells within a worksheet by holding down the CTRL key and then execute a script, my SELECTION statement seems to include all of the intermediate cells. Is there a way to select in this fashion and then to be able to use only the non contiguous cells that have actually been selected?

Chabu
05-31-2011, 03:06 PM
Try this piec of code an examine the results in the immediate window
Public Sub selectOpv()
Dim X As Range
For Each X In Application.Selection
Debug.Print X.Address
Next X
End Sub

Opv
05-31-2011, 03:11 PM
Try this piec of code an examine the results in the immediate window
Public Sub selectOpv()
Dim X As Range
For Each X In Application.Selection
Debug.Print X.Address
Next X
End Sub
Interesting. That is showing only the selected cells.

EDIT: Thanks, that helped me figure out my problem. I've got it working now.

Chabu
05-31-2011, 03:24 PM
I hope it helps :-)

Opv
05-31-2011, 03:31 PM
I hope it helps :-)

Indeed, it did. I edited my previous post to say that but I guess my edit didn't get posted in time for you to see it before your post. Thanks for your help.

mikerickson
05-31-2011, 04:39 PM
The problem with discontinuous ranges is that if you do almost anything with them, like .Offset, they become continous. Similarly setting the .Value.

If you want code that accepts a users selection of a discontinouse range, you'll probably have to have a structure like:
Dim oneArea as Range

For each oneArea in Selection.Areas
Rem some code
Next oneArea

Opv
05-31-2011, 04:45 PM
The problem with discontinuous ranges is that if you do almost anything with them, like .Offset, they become continous. Similarly setting the .Value.

If you want code that accepts a users selection of a discontinouse range, you'll probably have to have a structure like:
Dim oneArea as Range

For each oneArea in Selection.Areas
Rem some code
Next oneArea

Thanks. After I compared Chabu's sample to my test code I couldn't initially figure out why his worked and mine didn't. Your point is precisely why.