Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get start range and end range of a vertically merged cell with Excel using VBA

Tags:

excel

vba

I need to find out the first cell and the last cell of a vertically merged cell..

Let's say I merge Cells B2 down to B50.
How can I get in VBA the start cell(=B2) and the end cell(=B50)?

like image 676
vbauser Avatar asked Jun 01 '10 15:06

vbauser


People also ask

Does VBA work with merged cells?

In VBA, there is a “MERGE” method that you can use to merge a range of cells or even multiple ranges into one. This method has an argument “Across” which is optional. If you specify TRUE it will merge each row in the range separately, and if you specify FALSE it will merge the entire range as one.

Can you Vlookup a merged cell?

The Vlookup function will work in merged cells as usual in Google Sheets, but the output won't be what you are seeking. What's the solution to it? For example, if an item has three prices based on its grade, we may enter such data as below. Item: Mango (A1:A3 merged and entered it).


2 Answers

Sub MergedAreaStartAndEnd()

    Dim rng As Range
    Dim rngStart As Range
    Dim rngEnd As Range

    Set rng = Range("B2")

    If rng.MergeCells Then

        Set rng = rng.MergeArea
        Set rngStart = rng.Cells(1, 1)
        Set rngEnd = rng.Cells(rng.Rows.Count, rng.Columns.Count)

        MsgBox "First Cell " & rngStart.Address & vbNewLine & "Last Cell " & rngEnd.Address

    Else

        MsgBox "Not merged area"

    End If

End Sub
like image 193
dendarii Avatar answered Sep 22 '22 23:09

dendarii


Below macro goes through all sheets in a workbook and finds merged cells, unmerge them and put original value to all merged cells.

This is frequently needed for DB applications, so I wanted to share with you.

Sub BirlesenHucreleriAyirDegerleriGeriYaz()
    Dim Hucre As Range
    Dim Aralik
    Dim icerik
    Dim mySheet As Worksheet

    For Each mySheet In Worksheets

    mySheet.Activate
    MsgBox mySheet.Name & “ yapılacak…”

    For Each Hucre In mySheet.UsedRange
        If Hucre.MergeCells Then
           Hucre.Orientation = xlHorizontal
           Aralik = Hucre.MergeArea.Address
           icerik = Hucre
           Hucre.MergeCells = False
           Range(Aralik) = icerik
        End If
    Next

 MsgBox mySheet.Name & " Bitti!!"

 Next mySheet
End Sub
like image 38
Mustafa Aksit Avatar answered Sep 22 '22 23:09

Mustafa Aksit