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

落花浮王杯 提交于 2019-12-03 06:46:07

问题


How to get the value of a merged cell of an excel having range address like "$B$4:$B$11" in vba


回答1:


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

Hence, you can get the value of merged cells in range B4:B11 in several ways:

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

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.




回答2:


Josh Brown gave (in a comment) what I think is the best answer:

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. Thanks Josh!




回答3:


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;

Make sure there are no spaces in the name. Example: defined_Name. Go to the desired cell you wish to see the output/result. In that cell, type: =defined_Name.

Press enter because your done.



来源:https://stackoverflow.com/questions/9407474/get-value-of-a-merged-cell-of-an-excel-from-its-cell-address-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!