Suppose I have 2 cells that are merged, lets say Sheet1!$A$1:$B$1
.
And lets say there's a piece of text that's centered across both cells. How do I programmatically update that value with VBA? I have a simple user form with a button, on button click, I want the cell to update.
I've tried grabbing the Range, but that doesn't seem to work.
To edit a merged cell, you must edit each cell individually. You can use auto fill to expedite this process but the first edit must be in the upper left of the merged region. To auto fill, make your edit in the upper-left cell then click outside to exit edit mode.
In VBA, there is a “MERGE” method that you can use to merge a range of cells or even multiple ranges into one. This method has an argument “Across” which is optional. If you specify TRUE it will merge each row in the range separately, and if you specify FALSE it will merge the entire range as one.
ActiveCell.FormulaR1C1 = “Whatever You Want” To change the text in a cell, first select it. In this example, cell A1 is being selected. Then change the value in the active cell to whatever you want, just put it between double apostrophes.
Step 1: Use the ActiveCell object to access the currently selected cell in the worksheet. Use ActiveCell. Value function object to write the required text. Step 2: Color the cell by using ActiveCell.
In addition to the other answers, it's worth noting that you can also use MergeArea
to update via either of the cells:
Range("A1").MergeArea.Value="New value"
Range("B1").MergeArea.Value="New value"
If the cell isn't merged then it will just ignore the MergeArea (ie. it treats it like a merged area with one cell...)
Use this function if you need to reference a cell that might or might not be part of a merged range:
Function Reference_cell_even_if_merged(Cell_Range As Range) As Range
If Cell_Range.MergeCells Then
Set Reference_cell_even_if_merged = Cell_Range.MergeArea
Else
Set Reference_cell_even_if_merged = Cell_Range
End If
End Function
If you have merged the cells, then you can only edit the value of the merged cells by referencing the upper left most cell.
So, if A1 and B1 are merged, the only way to change the date is:
Range("A1").value = "data"
Or
Cells(1,1).Value = "data"
Calling Range("B1").Value = "data"
will not change the visible text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With