问题描述
请原谅我是 VBA 的新手.
Pardon me as am a newbie in VBA.
有时我会使用
Dim r as Range
r = Range("A1")
其他时候我用
Set r = Range("A1")
有什么区别?我什么时候应该使用什么?
What is the difference? And when should I use what?
推荐答案
除非引用对象引用,否则没有理由使用 set
.仅在该上下文中使用它是一种很好的做法.对于所有其他简单数据类型,只需使用赋值运算符.然而,dim
(维度)所有变量是个好主意:
There's no reason to use set
unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea to dim
(dimension) ALL variables however:
简单数据类型的示例包括 integer
、long
、boolean
、string
.这些只是数据类型,没有自己的方法和属性.
Examples of simple data types would be integer
, long
, boolean
, string
. These are just data types and do not have their own methods and properties.
Dim i as Integer
i = 5
Dim myWord as String
myWord = "Whatever I want"
object
的一个例子是 Range
、Worksheet
或 Workbook
.这些都有自己的方法和属性.
An example of an object
would be a Range
, a Worksheet
, or a Workbook
. These have their own methods and properties.
Dim myRange as Range
Set myRange = Sheet1.Range("A1")
如果您尝试使用没有Set
的最后一行,VB 将抛出错误.现在您已经声明了一个 object
,您可以访问它的属性和方法.
If you try to use the last line without Set
, VB will throw an error. Now that you have an object
declared you can access its properties and methods.
myString = myRange.Value
这篇关于vba中dim和set有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!