How do I detect if a cell is merged?
If the cell is merged how do I read the value?
How do I detect if a cell is merged?
If the cell is merged how do I read the value?
I don't think there's any formula to tell you if a cell is merged or not. You can write your own public vba function, put it in a code Module, and then use that on your sheet:
Function IsMerged(rCell As Range) As Boolean
' Returns true if referenced cell is Merged
IsMerged = rCell.MergeCells
End Function
Then as an Excel formula to test cell A1:
=IsMerged(A1)
Here's how to read the cell's value in VBA, regardless if it is merged or not.
C.MergeArea.Cells(1, 1).Value
where C is the cell you want to look at. The way this works is that the MergeArea is either exactly the same as the cell itself if the cell is not merged; otherwise the MergeArea is the range of cells that have been merged. And when the cells are merged, the value is kept in the topleftmost cell.
Hurray! Figured out a way to check whether a cell is merged and return that cell's value:
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
If B and C are always populated there is a simple non-VBA method to determine if a cell is merged. Simply do COUNTA(B2,C2) and check the total. If B2 is merged with C2, the total will be 1, if it's not the count will be 2.
A common need is to target only the first cell in a merged range. This code does that.
The If statement result is only true for the first cell; merged or not.
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
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")
I have written a little SUDOKU sheet and I use a macro to test if a cell is merged or not.
If a cell is already merged it contains a found digit and I don't use it.