7

How do I detect if a cell is merged?

If the cell is merged how do I read the value?

4

6 回答 6

13

我认为没有任何公式可以告诉您单元格是否已合并。您可以编写自己的公共函数,将其放入代码模块中,然后在工作表上使用它:

Function IsMerged(rCell As Range) As Boolean
' Returns true if referenced cell is Merged        
          IsMerged = rCell.MergeCells        
End Function

然后作为一个 Excel 公式来测试单元格A1

=IsMerged(A1)
于 2013-01-30T09:38:49.103 回答
4

这是在 VBA 中读取单元格值的方法,无论它是否被合并。

C.MergeArea.Cells(1, 1).Value

C您要查看的单元格在哪里。其工作方式是,如果单元格未合并,则 MergeArea 要么与单元格本身完全相同;要么 否则 MergeArea 是已合并的单元格范围。合并单元格时,该值保留在最左上角的单元格中。

于 2016-10-10T13:48:44.500 回答
1

欢呼!想出一种方法来检查一个单元格是否被合并并返回该单元格的值:

Sub checkCellMerged1()
'With ThisWorkbook.ActiveSheet
Set ma = ActiveCell.MergeArea

On Error GoTo errHand
If ma = ActiveCell Then MsgBox ActiveCell.Address & " is not merged"
GoTo final

errHand:
If Err.Number = 13 Then MsgBox "Merged Address = " & ma.Address _
& vbCrLf & "Value = " & ma(1).Value

final:
On Error GoTo 0
'End With
End Sub
于 2014-10-10T09:58:16.543 回答
0

如果总是填充 B 和 C,则有一个简单的非 VBA 方法来确定单元格是否被合并。只需执行 COUNTA(B2,C2) 并检查总数。如果 B2 与 C2 合并,则总数为 1,否则计数为 2。

于 2015-04-06T15:03:16.383 回答
0

一个常见的需求是仅针对合并范围中的第一个单元格。这段代码就是这样做的。

If 语句结果仅对第一个单元格为真;合并与否。

Sub RunOnlyForFirstCell()
    Dim c As Range
    Dim MergedCellsArea As Range
    
    For Each c In Selection.Cells
        Set MergedCellsArea = c.MergeArea
        If c.Address = MergedCellsArea(1, 1).Address Then
            '''run your sub
            Debug.Print c.Address; Selection.Cells.Count; MergedCellsArea(1, 1).Address
        End If
    Next c
 End Sub
于 2021-06-04T15:09:43.113 回答
0

以下代码回答了这两个问题

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

我写了一个小数独表,我使用一个宏来测试一个单元格是否被合并。

在此处输入图像描述

如果一个单元格已经合并,它包含一个找到的数字,我不使用它。

于 2021-11-17T16:06:00.777 回答