Vba excel определить объединенную ячейку

Не совсем понятна задача.
Проверить, объединена ли ячейка с другой (другими):

If Worksheets("Лист1").Cells(1, 3).MergeCells Then MsgBox "Таки да!"

При объединении значение ячеек, кроме левой верхней, теряются. В таком случае для создания списка для ComboBox не обязательно проверять, объединены ли ячейки, достаточно проверить ячейки на наличие данных. Код, создающий список элемента формы:

Private Sub UserForm_Initialize()
Dim Rng As Range
Dim n
'        создать выпадающий список
    With Worksheets("Лист1")
        Set Rng = .Range("C1:H4") ' присвоить переменной диапазон "шапки" таблицы
    End With

    ' цикл по ячейкам
    For Each n In Rng.Value
        If n <> "" Then ' если в ячейке есть данные
            Me.ComboBox1.AddItem n ' добавить строку в список
        End If
    Next n
End Sub

P.S. В расчетных таблицах старайтесь по возможности не объединять ячейки, могут быть проблемы с вычислениями.

0 / 0 / 0

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

Сообщений: 5

1

Как узнать объединены ли ячейки

20.03.2012, 11:55. Показов 25586. Ответов 2


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

Здравствуйте. Помогите пожалуйста. Как определить объединены ли ячейки.
Задача такая перебирая строки в таблице определить объединены ли столбцы (например первый и второй столбец), если да то одно действие а если нет то производить какие либо действия. Заранее спасибо.



0



15136 / 6410 / 1730

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

Сообщений: 9,999

20.03.2012, 12:05

2

cell.mergecells — входит в объединение или нет, true/false
cell.mergearea — диапазон объединения



0



0 / 0 / 0

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

Сообщений: 5

20.03.2012, 13:25

 [ТС]

3

Цитата
Сообщение от Казанский
Посмотреть сообщение

cell.mergecells — входит в объединение или нет, true/false
cell.mergearea — диапазон объединения

спасибо а можно в коде показать?

Добавлено через 32 минуты
все разобрался. благодарю



0



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

Славик Шаров

@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)


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


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


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

14 апр. 2023, в 19:53

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

14 апр. 2023, в 19:53

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

14 апр. 2023, в 19:46

1000 руб./в час

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

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

Понравилась статья? Поделить с друзьями:
  • Vba excel определить кто открывал файл
  • Vba excel определить количество столбцов
  • Vba excel определить количество листов
  • Vba excel определить значение ячейки
  • Vba excel определить диапазон таблицы