我的程序中的许多行都是通过声明来完成的。有更有效的方法吗?

时间:2014-11-26 09:11:04

标签: vba

我尽量保持我的程序简短。但是我经常需要在一个过程中引用几个对象,而单独的分解最终会占用很多行。例如:

Dim wksSource As Worksheet
Set wksSource = GetSheetByCodename(ThisWorkbook, "wWorkspace")
Dim wksTarget As Worksheet
Set wksTarget = GetSheetByCodename(ThisWorkbook, "wSaved")

Dim loWorkspace As ListObject
Set loWorkspace = wksOmdömeslistor.ListObjects("tWorkspace")

Dim sKey As String
Dim dMatchPosition As Double

在上面的代码中我花了10行,程序还没有做任何事情。它应该是这样,还是更好的声明变量的方法?

2 个答案:

答案 0 :(得分:1)

您可以通过这种方式在一行声明变量:

Dim wksSource As Worksheet, wksTarget As Worksheet, loWorkspace As ListObject, sKey As String, dMatchPosition As Double

答案 1 :(得分:1)

实际上,这更像是编码风格的问题。但我建议你按照它的方式离开它。但是,我可能会将变量声明组合在一起。

Dim wksSource As Worksheet
Dim wksTarget As Worksheet
Dim loWorkspace As ListObject
Dim sKey As String
Dim dMatchPosition As Double

Set wksSource = GetSheetByCodename(ThisWorkbook, "wWorkspace")
Set wksTarget = GetSheetByCodename(ThisWorkbook, "wSaved")

Set loWorkspace = wksOmdömeslistor.ListObjects("tWorkspace")

任何程序员都可以阅读并了解正在发生的事情。而且,就像@Radek所说,你可以在一行上声明它们。不过,我会避免这样做。