Home » excel » arrays – Vba, select a dynamic matrix

arrays – Vba, select a dynamic matrix

Posted by: admin May 14, 2020 Leave a comment


I have a worksheet which contains a data matrix like the sample below:


This array is dynamically generated, so..I know the coordinates of the top left (non empty) cell, I want to find the coordinates of the top right (non empty) Cell

The first solution is to use the .offset and check each cell to the right if it’s not null but I find this way bad. I would like find a better way, more optimized.

Does it exist?

How to&Answers:

In your case you can use CurrentRegion property:

Sub test()
    With Range("B5").CurrentRegion            
        MsgBox .Address 'address of entire matrix            
        MsgBox .Cells(.Rows.Count, .Columns.Count).Address 'bottom right cell
    End With
End Sub


If the data is as you posted (an isolated block starting at B5). Then:

Sub dural()
    Dim r As Range
    Set r = Range("B5").CurrentRegion
    nLastColumn = r.Columns.Count + r.Column - 1
End Sub