使用 MergeArea 检测 VBA Excel 中的合并单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22075988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:53:13  来源:igfitidea点击:

Detect merged cells in VBA Excel with MergeArea

excelvbaexcel-vbamerge

提问by zirael

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.

我遇到了这个问题 - 我必须从 excel 表中检测水平和垂直合并的单元格。我必须存储第一个单元格坐标和合并区域的长度。我用两个 for 循环逐行遍历表。

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:

如何使用 MergeArea 属性来检测合并和非合并区域?如果单元格没有合并,它可能应该返回空范围,但是,这个:

"If currentRange Is Nothing Then"

“如果 currentRange 什么都没有,那么”

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

根本不工作。有任何想法吗?非常感谢。

回答by tbur

There are several helpful bits of code for this.

有几个有用的代码位。

Place your cursor in a mergedcell 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:$F

回答by David Metcalfe

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

虽然使用@tbur 所示的选定单元格很有用,但它也不是唯一可用的选项。

You can use Range()like so:

您可以像这样使用Range()

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():

或者,您可以使用Cells()

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