Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update text in a merged cell with VBA?

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.

like image 468
Fred Avatar asked Nov 17 '11 20:11

Fred


People also ask

How do I edit text in merged cells?

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.

Does VBA work with merged cells?

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.

How do you change text in VBA cell?

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.

How do you update a cell value in Excel VBA?

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.


3 Answers

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

like image 148
Tim Williams Avatar answered Oct 06 '22 01:10

Tim Williams


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
like image 28
nateAtwork Avatar answered Oct 06 '22 02:10

nateAtwork


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.

like image 35
Justin Self Avatar answered Oct 06 '22 01:10

Justin Self