excel范围似乎保留了有关其创建原因的信息

时间:2016-04-30 19:05:44

标签: excel vba

看看这个例子:我已经创建了一个“常规”范围 两个范围:一个通过调用“columns”属性,另一个通过调用“rows”属性。 现在,虽然它们似乎也是常规范围,虽然它们引用相同的工作表区域,但默认方法的行为却不同。

Public Sub RangeTest01()

Dim r As Range

' i get a 'regular' range on the active sheet of 3 columns and 3 rows
Set r = ActiveSheet.Range("A1:C3")

Dim rr As Range
Set rr = r.Rows
Debug.Print "rr: range generated by the call 'Rows' on the original range"
Debug.Print "1. what kind of object is it? " & TypeName(rr)
Debug.Print "2. what are the sheet cell it refers to? " & rr.Address
Debug.Print "3. what does the default method call produce?" & rr(1).Address

Dim rc As Range
Set rc = r.Columns
Debug.Print "rc: range generated by the call 'Columns' on the original range"
Debug.Print "1. what kind of object is it? " & TypeName(rc)
Debug.Print "2. what are the sheet cell it refers to? " & rc.Address
Debug.Print "3. what does the default method call produce?" & rc(1).Address
End Sub

输出

rr: range generated by the call 'Rows' on the original range

1. what kind of object is it? Range
2. what are the sheet cell it refers to? $A$1:$C$3
3. what does the default method call produce?$A$1:$C$1

rc: range generated by the call 'Columns' on the original range

1. what kind of object is it? Range
2. what are the sheet cell it refers to? $A$1:$C$3
3. what does the default method call produce?$A$1:$A$3

问题

因此,并非所有相同数据的范围都是“相同的”,我在这里看到的关于行为的最佳描述是“范围保留了有关其创建原因的信息”,并且根据这些信息表现不同。

因此,如果它是为了处理列而创建的,那么它会保留一种“基于列的”标志,如果它是为了处理行而创建的,则相反。

问题是: 这条信息可以访问吗?是否存在其他“变化”类型的范围或其他对象应该在它们起源的地方查看它们的行为?

2 个答案:

答案 0 :(得分:0)

您正在创建一个包含由列对象或行对象拆分的一系列范围的对象,它们的行为方式不同,因为您已使用不同的方法定义它们。

如果您执行{{1}}并运行相同的进程,我确信它会输出 $ A $ 1:第3点$ 1澳元。或者只是$ A $ 1 - 会很有趣。

答案 1 :(得分:0)

我不知道一种方法可以将不同的创建范围区分开来,但另一方面我不认为这是必要的。

由于范围对象是包含(有序)其他范围集的类似集合的对象,因此可以通过索引对其进行迭代和寻址。 让我们看一下以下范围属性,这些属性根据它们应用的范围自行返回另一个范围对象:

  • Rows - 包含当前范围的所有单元格,分为单行
  • Columns - 包含当前范围的所有单元格,分为单列
  • Cells - 包含当前范围的所有单元格,一个接一个地划分为单个单元格(如果迭代它,则逐列获取第一行的单元格,然后对第二行进行相同的操作)等等)
  • EntireRow - 包含工作表中的所有单元格除以行数,但仅包含当前范围涵盖的那些行:考虑当前范围扩展到所有列
  • EntireColumn - 包含工作表中的所有单元格除以列,但只包含当前范围涵盖的那些列:考虑当前范围扩展到所有行

因此,根据属性,返回值将使单元格被不同地“切割”成可以由索引迭代或寻址的部分。但是所有属性仍然返回相同的单元格,只是以不同的顺序排序(除了整个*属性,它们也返回其各自行/列中的所有其他单元格)。

现在,如果你必须处理一个范围对象但不知道如何创建范围,只需将上述任何属性应用于它,让它以你喜欢的方式返回单元格。 由于所有这些范围属性本身都会返回范围,因此您可以多次应用它们 例如,考虑更改您的代码:

Set rr = r.Rows.Columns
...
Set rc = r.Columns.Rows

输出相同,只在两个块之间切换。成为列列表之前的行列表是什么,反之亦然。