Passing contiguous / non-contiguous selected cells to an array

RawlinsCross

Active Member
Joined
Sep 9, 2016
Messages
437
Good day,

Have a worksheet where I'd like to select cells in column A (they could be contiguous or non-contiguous) and place the values in an array.

Seems simple enough (vArray = Selection.value works for contiguous selection a group of cells) but I'm having trouble with the non-contiguous part. If I select say A1, A3, A5 using the ctrl-key the resulting array (using vArray = Selection.value) contains only A1. Any thoughts on something that can handle both contiguous AND non-contiguous cases?
 

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
If you have selected various cells in column (contiguous or non-contiguous), the following should put them all in an array:
VBA Code:
Sub BuildArray()

    Dim arr() As Variant
    Dim cell As Range
    Dim n As Long
    
    ReDim arr(1 To 10000)
    n = 0
    
    For Each cell In Selection
        n = n + 1
        arr(n) = cell.Value
    Next cell
    
    ReDim Preserve arr(1 To n)
    
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,223,231
Messages
6,170,884
Members
452,364
Latest member
springate

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top