Как проверить ячейка в excel объединена в vba

The following code is answering to both questions

Function GetValue(iRow As Integer, iCol As Integer) As String
    Dim rCell As Range
    Set rCell = oSheet.Cells(iRow, iCol)
        
    sText = ""
            
    If Not rCell.MergeCells Then
        sText = rCell.Value
    End If
        
    GetValue = sText
End Function
...
Set oSheet = Worksheets("Sheet1")

Using Excel, I have written a little SUDOKU sheet and I use a VBA macro to test if a range of cells has been merged or not.

enter image description here

In following example (above image), I use following code to detect empty Sudoku cells and try to resolve unfound digit.

If a cell (Excel 3×3 range) is merged it contains a found digit.

'**********************************************************************
'* HighlightFoundCells()
'*-------------------------------------------------
'* When a Sudoku Cell (3x3 Excel range) contains only 1 small digit,
'* it is displayed using bigger font in middle of merged 3x3 Excel range
'**********************************************************************

For n = 1 To 9
    For i = 1 To 9
        iCount = 0
        For j = 1 To 9
            If GetDigitValue(n, i, j) = n Then
                iCount = iCount + 1
                jLast = j
            End If
        Next j
        If iCount = 1 Then
            Call MergeCells(iFirstRow + 3 * (i - 1), iFirstCol + 3 * (jLast - 1))
            ActiveCell.FormulaR1C1 = CStr(n)
            Call HighlightCell(iLast, j)
        End If
    Next i
Next n

'**********************************************************************
'* GetDigitValue()
'*---------------------------------------------------------------------
'* Get digit value contained in merged 3x3 cell's range
'* that represent a found digit.
'**********************************************************************

Function GetDigitValue(n As Integer, iRow9 As Integer, iCol9 As Integer) As Integer
    row = iFirstRow + (iRow9 - 1) * 3 + (n - 1)  3
    col = iFirstCol + (iCol9 - 1) * 3 + (n - 1) Mod 3
    
    Dim rCell As Range
    Set rCell = oSheet.Cells(row, col)
    
    Dim c As Integer: c = 0
        
    If Not rCell.MergeCells Then
        c = rCell.Value
    End If
    
    GetDigitValue = CInt(c)
End Function

'**********************************************************************
'* HighlightCell()
'*---------------------------------------------------------------------
'* Change background of 3x3 group of cells that contains a found digit
'**********************************************************************

Sub HighlightCell(i As Integer, j As Integer)
    nRow = iFirstRow + (i - 1) * 3
    nCol = iFirstCol + (j - 1) * 3
    oSheet.Range(Cells(nRow, nCol), Cells(nRow + 2, nCol + 2)).Select
    
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub

Excel code to merge a range of cells is following

Sub MergeCells(iRow As Integer, iCol As Integer)
    Range(oSheet.Cells(iRow, iCol), oSheet.Cells(iRow + 2, iCol + 2)).Select
    Selection.ClearContents
    'Range("X8").Select
    'ActiveCell.FormulaR1C1 = "5"
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = True
    End With
    Selection.Merge
    With Selection.Font
        .Name = "Arial"
        .Size = 48
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ColorIndex = xlAutomatic
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With
End Sub

I’m having quite an issue with this one — I have to detect horizontally and vertically merged cells from an excel table. I have to store the first cell coords, and the lenght of the merged area. I iterate through the table with two for-cycles, line by line.

How can I use MergeArea property to detect the merged and non-merged areas?
If the cell is not merged, it should probably return empty range, however, this:

«If currentRange Is Nothing Then»

is not working at all. Any ideas?
Thanks a lot.

asked Feb 27, 2014 at 17:32

zirael's user avatar

ziraelzirael

3931 gold badge3 silver badges4 bronze badges

1

2 Answers

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What’s the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

answered Feb 27, 2014 at 18:05

tbur's user avatar

tburtbur

2,3741 gold badge13 silver badges12 bronze badges

1

While working with selected cells as shown by @tbur can be useful, it’s also not the only option available.

You can use Range() like so:

If Worksheets("Sheet1").Range("A1").MergeCells Then
  Do something
Else
  Do something else
End If

Or:

If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
  Do something
Else
  Do something else
End If

Alternately, you can use Cells():

If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
  Do something
Else
  Do something else
End If

answered May 1, 2018 at 3:09

David Metcalfe's user avatar

David MetcalfeDavid Metcalfe

2,1471 gold badge27 silver badges43 bronze badges

I have an Excel document that contains duty shifts. I would like to findout if there is any merged cells like given below withing given range..

Example

How can I determine the cells are filled in given range or the cells are merged in given range?

If IsEmpty(Range("NewRange")) = False Then
    z = z + 1 'My counter 
End If

I tried IsEmpty Function but it doesnt work correctly on merged cells. You can try but the result is same.. While I got a block of empty cells there it counts as filled..

asked Feb 12, 2015 at 14:10

Berker Yüceer's user avatar

Berker YüceerBerker Yüceer

6,98618 gold badges67 silver badges102 bronze badges

1

Славик Шаров

@spark36

Полная комплектация: 2 руки, 2 ноги, голова, мозги

Как проверить диапазон ячеек объединен или нет?

Получаю в методе диапазон ячеек
Excel.Range cells = ws.Range[start, end];
Как можно проверить объединен ли он в одну ячейку или нет?


  • Вопрос задан

    более трёх лет назад

  • 586 просмотров


Комментировать

Пригласить эксперта


Ответы на вопрос 1

honor8

h8nor

@honor8

Принципы быстродействия VBA в описании

Если нужно проверить, объединена ли ячейка B1 с другими в один диапазон, то для VBA код будет:

merge = Cells(1, 2).MergeArea.Address(RowAbsolute:=False, ColumnAbsolute:=False)


Комментировать


Похожие вопросы


  • Показать ещё
    Загружается…

15 апр. 2023, в 23:37

1000 руб./в час

15 апр. 2023, в 23:24

25000 руб./за проект

15 апр. 2023, в 21:40

2000 руб./за проект

Минуточку внимания

0 / 0 / 0

Регистрация: 05.05.2006

Сообщений: 11

1

Нужно проверить объединены ли ячейки?

25.06.2006, 00:35. Показов 5625. Ответов 5


Студворк — интернет-сервис помощи студентам

Ячейка может не входить в объединение ячеек, может быть объединена с соседними. Например, ячейка А1 может быть объединена с ячейками B1 и C1, еще может быть обединена с ячейками B1, C1, D1 и E1, а может и не входить в объединение.. как это проверить?? в последствии необходимо задать условие, что если объединена с B1 и C1, то делаем то-то, а если с B1, C1, D1 и E1 — то то-то..
Здесь надо использовать свойства MergeCells или нет??



0



VladDudka

0 / 0 / 0

Регистрация: 05.05.2006

Сообщений: 11

25.06.2006, 01:08

 [ТС]

2

Поэкспериментировал и получилось сделать вот так вот..

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Set mb = Range("a15")
Set ma = Range("a1").MergeArea
If ma.Address = "$A$1" Then
    mb.Value = "months"
Else
    If ma.Address = "$A$1:$C$1" Then
    mb.Value = "quartals"
    Else
        If ma.Address = "$A$1:$L$1" Then
        mb.Value = "years"
        Else
        mb.Value = "months"
        End If
    End If
End If

Но у меня проблема возникла, я не могу задать Range через Range(cells (1, 1), пишет ошибку.. а мне именно так надо, потому что я адрес ячейки передаю переменной.



0



5 / 5 / 3

Регистрация: 17.10.2007

Сообщений: 1,119

25.06.2006, 08:15

3

<A class=SmlBoldLinks id=ctl03_ctlTopic_ctlPanelBar_ctlTopicsRepeater_ct l06_smAuthorName onmouseover=»window.status = window.location;return true;» title=»View VladDudka’s Profile…» onmouseout=»window.status=»return true;» href=»void(»); VladDudka,
Все-таки непонятно, что именно именно так надо и для чего, и в какой строке ошибка.
VladConn



0



VladDudka

0 / 0 / 0

Регистрация: 05.05.2006

Сообщений: 11

25.06.2006, 19:13

 [ТС]

4

У меня есть две переменных

Visual Basic
1
2
3
4
Dim wcnt1 As Integer
Dim wcnt2 As Integer
wcnt1 = 1
wcnt2 = 5

И надо сделать вот так вот
If cells (wcnt1, 1) не объединена ни с одной ячейкой then
ячейке (wcnt2, 15) присваивается значение «months»
If cells (wcnt1, 1) объединена с ячейками (wcnt1+1, 1) и (wcnt1+2, 1) then
ячейке (wcnt2, 15) присваивается значение «quartals»
ну и если она объединена с 1 по 12 ячейки, то значение — год…



0



VladConn

5 / 5 / 3

Регистрация: 17.10.2007

Сообщений: 1,119

26.06.2006, 09:10

5

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Private Sub CommandButton1_Click()
    SetPeriods 1, 5, 1, 15, 3, 12, 1
End Sub
Private Sub SetPeriods(ByVal plngRowOne As Long, _
                       ByVal plngRowTwo As Long, _
                       ByVal pintColumnOne As Integer, _
                       ByVal pintColumnTwo As Integer, _
                       ByVal pintMergedCountOne As Integer, _
                       ByVal pintMergedCountTwo As Integer, _
                       ByVal pintWSheet As Integer)
    Dim objCellOne As Range
    Dim objCellTwo As Range
    Dim objMergedRange As Range
    Dim objWSheet As Worksheet
        
    Set objWSheet = ThisWorkbook.Worksheets(pintWSheet)
    Set objCellOne = objWSheet.Cells(plngRowOne, pintColumnOne)
    Set objCellTwo = objWSheet.Cells(plngRowTwo, pintColumnTwo)
    
    If Not objCellOne.MergeCells Then
        objCellTwo.Value = "Months"
    Else
        Set objMergedRange = objCellOne.MergeArea
        Select Case True
            Case objMergedRange.Column = pintColumnOne And objMergedRange.Row = plngRowOne And objMergedRange.Rows.Count = pintMergedCountOne
                objCellTwo.Value = "Quarters"
            Case objMergedRange.Column = pintColumnOne And objMergedRange.Row = plngRowOne And objMergedRange.Rows.Count = pintMergedCountTwo
                objCellTwo.Value = "Year"
        End Select
    End If
        
    Set objWSheet = Nothing
    Set objCellOne = Nothing
    Set objCellTwo = Nothing
    Set objMergedRange = Nothing
    
End Sub



0



vlth

14 / 14 / 2

Регистрация: 23.03.2010

Сообщений: 635

26.06.2006, 22:14

6

Что-то я не понял, какие ячейки у тебя объединяются: в строке 1 или в столбце 1 ? Из первого описания — вроде бы в строке… Впрочем, неважно: в любом случае, наверное, надо сосчитать кол-во объединённых ячеек? Тогда так:

Visual Basic
1
2
3
4
5
6
7
Dim oMyCell As Range
Set oMyCell = Cells(5, 15)
Select Case Cells(1, 1).MergeArea.Count
    Case 1: oMyCell = "Month"
    Case 3: oMyCell = "Quarter"
    Case 12: oMyCell = "Year"
End Select

Дополнительно, для предотвращения ошибки, можно проверить MergeArea на кол-во содержащихся строк или столбцов (Cells(1, 1).MergeArea.Rows.Count).



0



Понравилась статья? Поделить с друзьями:
  • Как проверить электронную подпись на документе word
  • Как проверить шрифт в word
  • Как проверить что ячейка не пустая excel vba
  • Как проверить что число целое excel
  • Как проверить что текст не скопирован в word