为什么范围显然是数组? [英] Why is a Range apparently an Array?

查看:33
本文介绍了为什么范围显然是数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Excel VBA中的功能

In Excel VBA the function

IsArray(Range("A1:A5"))

对于包含一个以上单元格的任何范围(据我所知),将返回 True .

will return True for any range containing more than one cell (as far as I can tell).

这是为什么?其他可迭代对象(例如 Collection ArrayList )并非如此.以及如何修改我的数组检查代码以仅针对数组而不是类似数组的对象返回 True ?

Why is this? The same is not true other iterable objects like Collection and ArrayList. And how can I modify my array checking code to return True solely for arrays, not array-like objects?

推荐答案

范围是一个对象.

Debug.Print TypeName(Range("A1:A5")) ' prints "Range"

您正在做的是隐式默认成员调用,调用 Range.[_ Default] ,归结为调用 Range.Value ,...返回给定任何多单元格范围的2D数组.

What you're doing is an implicit default member call, invoking Range.[_Default], which boils down to invoking Range.Value, ...which returns a 2D array given any multiple-cell range.

Debug.Print IsArray(Range("A1").Value)    ' prints "False"
Debug.Print IsArray(Range("A1:A2").Value) ' prints "True"

该默认成员调用是在背后"进行的,因为VBA是有用的",并且看到您正在调用 IsArray(someObjectReference)后,转到该的界面someObjectReference ,看到它有一个默认成员,并计算 IsArray(someObjectReference.DefaultMember)而不是 IsArray(someObjectReference),这没有用(显然,对象引用 不是数组...对吧?).

That default member call is made "behind your back" because VBA is "being helpful" and, seeing that you're invoking IsArray(someObjectReference), goes to the interface of that someObjectReference, sees that there's a default member for it, and evaluates IsArray(someObjectReference.DefaultMember) instead of IsArray(someObjectReference), which wouldn't be useful (an object reference obviously isn't an array... right?).

对于其他暴露默认成员的类/类型,您将获得类似的结果. Application String 吗?

You get similar results with other classes/types that expose a default member. Is Application a String?

Debug.Print Application ' prints "Microsoft Excel"

当然不是-它是一个对象,但是具有默认成员,该成员在被调用时归结为调用其 Name 属性getter.

Of course not - it's an object, but with a default member that, when invoked, boils down to invoking its Name property getter.

分配对象引用时,需要 Set 关键字:

When assigning an object reference, the Set keyword is required:

Dim foo As Variant
Set foo = Range("A1")

如果没有 Set 关键字,则将相同的代码分配给返回对象的默认成员:

Without the Set keyword, the same code would be assigning to the returned object's default member:

Dim foo As Variant
foo = Range("A1") '.Value is implicit

写出说明其作用并按其说明的代码-尽可能避免隐式默认成员调用.

Write code that says what it does, and does what it says - avoid implicit default member calls where possible.

这篇关于为什么范围显然是数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆