我可以在 VBA 中同时声明和分配一个变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3256122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:38:36  来源:igfitidea点击:

Can I simultaneously declare and assign a variable in VBA?

vbavariable-declaration

提问by Ian R. O'Brien

I'm new to VBA and want to know if I can convert the following declaration and assignment into one line:

我是 VBA 新手,想知道是否可以将以下声明和赋值转换为一行:

Dim clientToTest As String
clientToTest = clientsToTest(i)

or

或者

Dim clientString As Variant
clientString = Split(clientToTest)

回答by Alex K.

There is no shorthand in VBA unfortunately, The closest you will get is a purely visual thing using the :continuation character if you want it on one line for readability;

不幸的是,VBA 中没有速记,:如果您希望将其放在一行以提高可读性,那么您将获得的最接近的是使用连续字符的纯粹视觉效果;

Dim clientToTest As String:  clientToTest = clientsToTest(i)
Dim clientString As Variant: clientString = Split(clientToTest)


Hint (summary of other answers/comments): Works with objects too (Excel 2010):

提示(其他答案/评论的摘要):也适用于对象(Excel 2010):

Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim ws2 As New Worksheet: ws2.Name = "test"

回答by John M Gant

You can sort-of do that with objects, as in the following.

您可以对对象进行排序,如下所示。

Dim w As New Widget

But not with strings or variants.

但不适用于字符串或变体。

回答by Patrick Lepelletier

in fact, you can, but not that way.

事实上,你可以,但不是那样。

Sub MySub( Optional Byval Counter as Long=1 , Optional Byval Events as Boolean= True)

'code...

End Sub

And you can set the variables differently when calling the sub, or let them at their default values.

您可以在调用 sub 时以不同的方式设置变量,或者让它们使用默认值。

回答by Vadzim

In some cases the whole need for declaring a variable can be avoided by using Withstatement.

在某些情况下,使用Withstatement可以避免声明变量的全部需要。

For example,

例如,

    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogSaveAs)
    If fd.Show Then
        'use fd.SelectedItems(1)
    End If

this can be rewritten as

这可以重写为

    With Application.FileDialog(msoFileDialogSaveAs)
      If .Show Then
        'use .SelectedItems(1)
      End If
    End With