从合并的单元格中获取值的奇怪行为

时间:2014-06-12 15:02:31

标签: vba excel-vba excel-2010 excel

我在Excel中遇到过这种行为。鉴于这些细胞:

        A         B         C         D
   |---------|---------|---------|---------|
 1 | merged cell text  | foo     | bar     |
   |---------|---------|---------|---------|
 2 |         |         |         |         |
   |---------|---------|---------|---------|

选择单元格C1 foo)时,以下VBA语句返回空字符串

Debug.Print Selection.Offset(0, -1).Range("A1").Value

然而,下一个VBA会返回预期值(merged cell text):

Selection.Offset(0, -1).Select
Debug.Print Selection.Range("A1").Value

我无法终身为什么 - 当Offset返回RangeSelection也是Range时它只是在多行中分解相同的行为,并获得不同的结果。当没有合并的单元格时,不会发生这种行为。

有谁能解释这里发生了什么?

2 个答案:

答案 0 :(得分:1)

这应该是原因:

Debug.Print Selection.Offset(0, -1).Range("A1").Value  

您当前的选择是C1,偏移-1列给您B1。您正在尝试在选择B1时打印A1的值,因此不提供任何内容。合并单元格不会自动导致选择A1和B1 (您可以通过打印B1的值来测试)。但是:

Selection.Offset(0, -1).Select
Debug.Print Selection.Range("A1").Value  

首先选择范围B1,合并后,使其在应用程序级别选择A1和B1,从而能够打印A1的值

希望你能清楚

答案 1 :(得分:1)

如果你想从mergedcell的任何地方读取a1中的值,

Debug.Print Range("anyCellFormMergedRange").cells(1,1).Value  'wich gets the value from the first cell of a bigger range (here A1:B1)

Debug.Print Range("anyCellFormMergedRange").MergeArea(1, 1).value 'wich gets the value from the first cell of a MERGED range (here A1:B1)
'for a small mergedcell like yours, a simple .mergearea(1) works too

您可以将范围更改为您需要的任何内容(选择,.offset(x,y),activecell ...)也是范围。

如果你想使用整个mergedCells(A1:B1),而不使用.select:

(来自C1)

    Debug.Print selection.offset(0,-1).MergeArea.address

还要记住,评论,验证数据也包含在范围的第一个单元格中(此处为A1)。

相关问题