简体   繁体   English

从 vba 中的单元格地址获取 excel 的合并单元格的值

[英]Get value of a merged cell of an excel from its cell address in vba

How to get the value of a merged cell of an excel having range address like "$B$4:$B$11" in vba如何获取 excel 的合并单元格的值,其范围地址如 vba 中的“$B$4:$B$11”

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it). 即使真的不鼓励在Excel中使用合并单元格(例如,如果需要,使用Center Across Selection ),“包含”该值的单元格是左上角的单元格(至少,这是表达它的方式)。

Hence, you can get the value of merged cells in range B4:B11 in several ways: 因此,您可以通过以下几种方式获取B4:B11范围内合并单元格的值:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. 您还可以注意到所有其他单元格中没有任何值。 While debugging, you can see that the value is empty . 在调试时,您可以看到该值为empty

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array. 另请注意Range("B4:B11").Value不起作用(如果尝试Debug.Print它会引发执行错误号13),因为它返回一个数组。

Josh Brown gave (in a comment) what I think is the best answer: Josh Brown(评论中)给出了我认为最好的答案:

When I don't know the bounds of the merged area, I get the value with 当我不知道合并区域的边界时,我得到了值

Range("B6").MergeArea.Cells(1,1).Value

This is helpful in VBA when, for example, you are looping through files that might have merged cells of unknown ranges, so you can be much more general with this method. 例如,当您循环浏览可能已合并未知范围的单元格的文件时,这在VBA中很有用,因此您可以使用此方法更加通用。 Thanks Josh! 谢谢Josh!

This can be done in 2 steps: 这可以分两步完成:

First name the range of the merged cells; 首先命名合并单元格的范围; highlight the merged cell then go on the Ribbon Bar: Formulas Tab --> Define Name; 突出显示合并的单元格然后进入功能区栏: Formulas Tab --> Define Name;

Make sure there are no spaces in the name. 确保名称中没有空格。 Example: defined_Name . 示例: defined_Name Go to the desired cell you wish to see the output/result. 转到您希望查看输出/结果的所需单元格。 In that cell, type: =defined_Name . 在该单元格中,键入: =defined_Name

Press enter because your done. 按Enter键,因为你完成了。

(Excel 2016) (Excel 2016)

I am hoping this will help somebody.我希望这会对某人有所帮助。

I have found that if you press delete on a merged cell, the target.cells.count = the number of merged cells.我发现如果您在合并的单元格上按删除键,则 target.cells.count = 合并单元格的数量。

Whereas if you change the value on the same cell, the target.cells.count = 1而如果您更改同一单元格上的值,则 target.cells.count = 1

This caused me issues as I was skipping multi selections in my worksheet_change code by testing the number of cells selected.这给我带来了问题,因为我通过测试所选单元格的数量来跳过 worksheet_change 代码中的多项选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM