vba中的dim和set之间有什么区别? [英] What is the difference between dim and set in vba

查看:359
本文介绍了vba中的dim和set之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

赦免我是VBA的新手。



有时我使用

  Dim r as Range 
r =范围(A1)

其他时间我使用

 设置r =范围(A1)



<有什么区别?什么时候应该使用什么?

解决方案

没有理由使用 set 除非引用对象引用。在这种情况下只能使用它是一个很好的做法。对于所有其他简单的数据类型,只需使用赋值运算符。这是一个好主意, dim (维)所有变量:



简单数据类型的示例将是 integer long boolean string 。这些只是数据类型,没有自己的方法和属性。

  Dim i as Integer 
i = 5

Dim myWord as String
myWord =无论我想要什么

对象的示例将是范围工作表工作簿。这些有自己的方法和属性。

  Dim myRange as Range 
设置myRange = Sheet1.Range(A1)

如果您尝试使用没有 Set 的最后一行,VB将抛出错误。现在,您有一个对象声明您可以访问其属性和方法。

  myString = myRange.Value 


Pardon me as am a newbie in VBA.

Sometimes I use

Dim r as Range
r = Range("A1")

Other times I use

Set r = Range("A1")

What is the difference? And when should I use what?

解决方案

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:

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"

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")

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之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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