如何使用 VBA 更新合并单元格中的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8173877/
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 12:11:17  来源:igfitidea点击:

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

excel-vbaexcel-2007vbaexcel

提问by Fred

Suppose I have 2 cells that are merged, lets say Sheet1!$A$1:$B$1.

假设我有 2 个合并的单元格,比如说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.

假设有一段文本以两个单元格为中心。如何使用 VBA 以编程方式更新该值?我有一个带按钮的简单用户表单,单击按钮时,我希望单元格更新。

I've tried grabbing the Range, but that doesn't seem to work.

我试过抓住 Range,但这似乎不起作用。

回答by Tim Williams

In addition to the other answers, it's worth noting that you can also use MergeAreato update via either of the cells:

除了其他答案之外,值得注意的是,您还可以使用MergeArea通过任一单元格进行更新:

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

如果单元格未合并,则它只会忽略 MergeArea(即,它将其视为具有一个单元格的合并区域......)

回答by Justin Self

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:

因此,如果 A1 和 B1 合并,则更改日期的唯一方法是:

Range("A1").value = "data"

Range("A1").value = "data"

Or

或者

Cells(1,1).Value = "data"

Cells(1,1).Value = "data"

Calling Range("B1").Value = "data"will not change the visible text.

调用Range("B1").Value = "data"不会改变可见文本。

回答by Michael Kingsmill

You can set the value of the first cell and it will update the text.

您可以设置第一个单元格的值,它将更新文本。

Worksheets("Sheet1").Cells(1,1).Value = "New Value"

回答by nateAtwork

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