Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA Excel SelectionChange Reading Target Range into array and returning column count

When a new selection of cells is made, I want to convert the range into an array for later use, and determine the number of columns selected. This is the code I have, but I get a type mismatch error. Can someone point me in the right direction?

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim arr As Variant
    Dim colcount As Long
    arr = Target
    colcount = UBound(arr, 2)
    Debug.Print colcount
End Sub

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The error is due to Range.Value returning only a single value when the range only has a single cell.

If Target is a single cell, then Target will return a single value instead of an array. arr will be a single value and UBound(arr, 2) will error because arr is not an array.

You can use IsArray to check if arr is an array or not before attempting UBound. Also, if you intend to save these values for future use, you should define them as Module-Level variables.

Dim arr As Variant
Dim colcount As Long

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    arr = Target
    If IsArray(arr) Then
        colcount = UBound(arr, 2)
    Else
        colcount = 1
    End If
    Debug.Print colcount
End Sub

To fill colcount, other than UBound, you could also just do colcount = Target.Columns.Count which would also avoid needing to check IsArray.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading