简体   繁体   English

Excel 2007 VBA范围变量引用分配范围外的单元格

[英]Excel 2007 VBA Range Variable References Cells Outside Assigned Range

I've searched everywhere but haven't been able to figure out why a range variable is able to reference cells outside the assigned range. 我到处搜索但是无法弄清楚为什么范围变量能够引用指定范围之外的单元格。

For example, if I write the code below: 例如,如果我写下面的代码:

 Dim Rate as Range
 Set Rate = Range("A1:A5") 

 For Each Cell In Rate
      Debug.Print Cell.Value
 Next Cell

 Range("H6").Value = Rate(6).Value
 Range("H7").Value = Rate(7).Value

The above routine will only print out the 5 values in "A1:A5" -- BUT the last 2 statements cause the values in "A6" and "A7" to get stored in "H6" and "H7". 上述程序仅打印出“A1:A5”中的5个值 - 但最后2个语句使“A6”和“A7”中的值存储在“H6”和“H7”中。

Since the variable "Rate" has only been assigned to "A1:A5", why is it able to reference other cells in column A (ie, "A6" & "A7")? 由于变量“Rate”仅被分配给“A1:A5”,为什么它能够引用A列中的其他单元格(即“A6”和“A7”)?

Am I doing something wrong? 难道我做错了什么? Any insight would be greatly appreciated! 任何见解将不胜感激!

Nothing wrong, it's just how it works. 没有错,它只是它的工作原理。 I personally like this "feature". 我个人喜欢这个“功能”。
If you rather get an error, then you can use something like 如果您更喜欢错误,那么您可以使用类似的东西

 Range("H6").Value = Rate.Value2(6, 1)  ' .Value2 because .Value(6, 1) 

because Rate.Value2 will give a 5 by 1 variant array. 因为Rate.Value2将提供一个5乘1的变体数组。 Or use the .Value array instead of the Range: 或者使用.Value数组而不是Range:

 Dim Rate ' as Variant
 Rate = Range("A1:A5").Value    ' Variant/Variant(1 To 5, 1 To 1)

 Debug.Print Rate(5, 1) ' ok
 Debug.Print Rate(6, 1) ' Run-time error '9': Subscript out of range

or 要么

 Dim Rate as Variant
 Rate = Application.Transpose(Range("A1:A5"))   ' Variant/Variant(1 To 5)

 Debug.Print Rate(5) ' ok
 Debug.Print Rate(6) ' Run-time error '9': Subscript out of range

In your case Rate(6) is short for Rate.Cells(6, 1) which is similar to .Offset . 在你的情况下, Rate(6)Rate.Cells(6, 1) Rate(6)的缩写,类似于.Offset For example: 例如:

 Debug.Print Range("C3:D4")( 1,  1).Address   ' prints "$C$3"
 Debug.Print Range("C3:D4")(-1, -1).Address   ' prints "$A$1"

The only way I can think of getting error with Range is to use Areas instead: 我能想到使用Range获取错误的唯一方法是使用区域代替:

Dim Rate As Areas
Set Rate = Range("a1,a2,a3,a4,a5").Areas

Debug.Print Rate(5) ' ok
Debug.Print Rate(6) ' Run-time error '9': Subscript out of range

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

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