Select defined levels
"... So i.e level 0 is ABCDE
, level 1 contains cell which merges columns BCDE
, level 2 merges only CDE
, level 3 DE
and level 4 is only E
."
This approach selects all items of a given Level
(as defined above) using the MergeCells
and MergeArea
properties to check for merged cells at the defined Level
via helper function bIsLevel()
.
Applied method
Basically it
- checks each cell
c
in a defined range *) whether it belongs to a merged cells range (If c.MergeCells Then ...
),
- gets the resulting
c.MergeArea.Address
,
- checks found addresses against the wanted level x address via helper function
bIsLevel()
Note to recent Edit in 1st loop condition
*) As MergeArea.Addresses
only show the first included range (top/left cell in merge range), it is possible to narrow the search range from e.g. .UsedRange
to the column therein corresponding to Level + 1
; therefore I edited For Each c In Intersect(.UsedRange, .Columns(Level + 1))
as new loop condition instead.
Calling the main procedure SelectLevel
Procedure SelectLevel
has two optional parameters: (1) the wanted Level as defined by OP, (2) the qualified worksheet name. It can be called by the following example statement (Note: if you don't assign the 1st argument, level 0
is assumed by default, the 2nd argument defaults to a worksheet name of your choice and should be changed to your a current sheet name).
SelectLevel 1 ' e.g. level 1 selects all merged cells of columns B:E
Main procedure SelectLevel
Sub SelectLevel(Optional Level& = 0, Optional ByVal SheetName$ = "MySheet")
Dim c As Range, rng As Range, i&
With ThisWorkbook.Worksheets(SheetName)
For Each c In Intersect(.UsedRange, .Columns(Level + 1))
If c.MergeCells Then
If c.Address = Left(c.MergeArea.Address, Len(c.Address)) Then
If bIsLevel(c, Level) Then
If rng Is Nothing Then
Set rng = c
Else
Set rng = Application.Union(rng, c)
End If
End If
End If
End If
Next
End With
' Execute selection of wanted level
If Not rng Is Nothing Then
rng.Select
Else
MsgBox "Found no LEVEL" & Level & " items.", vbExclamation, "No Selection"
End If
End Sub
Helper function bIsLevel()
Function bIsLevel(currCell As Range, ByVal lvl&) As Boolean
Dim LevelAddress$, CellAddress$
Dim arr(): arr = Array("A", "B", "C", "D", "E")
LevelAddress = arr(lvl) & ":" & arr(UBound(arr)) ' define Level columns due to OP
CellAddress = Split(currCell.MergeArea.Address, "$")(1) & ":" & _
Split(currCell.MergeArea.Address, "$")(3)
bIsLevel = (LevelAddress = CellAddress)
'If bIsLevel Then Debug.Print "cell " & currCell.Address & " in currcell.MergeArea " & currCell.MergeArea.Address & _
" (" & CellAddress & " equ./LEVEL" & lvl & " " & LevelAddress & ")"
End Function