代码之家  ›  专栏  ›  技术社区  ›  Ian R. O'Brien Mamedov

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

  •  145
  • Ian R. O'Brien Mamedov  · 技术社区  · 14 年前

    Dim clientToTest As String
    clientToTest = clientsToTest(i)
    

    Dim clientString As Variant
    clientString = Split(clientToTest)
    
    4 回复  |  直到 7 年前
        1
  •  256
  •   Rahul    5 年前

    在VBA中没有速记,不幸的是,使用 :

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

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

    Dim ws  As Worksheet: Set ws = ActiveWorkbook.Worksheets("Sheet1")
    Dim ws2 As New Worksheet: ws2.Name = "test"
    
        2
  •  23
  •   John M Gant aman_novice    14 年前

    您可以对对象执行类似的操作,如下所示。

    Dim w As New Widget
    

    但不是字符串或变体。

        3
  •  2
  •   Patrick Lepelletier    9 年前

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

    Sub MySub( Optional Byval Counter as Long=1 , Optional Byval Events as Boolean= True)
    
    'code...
    
    End Sub
    

    在调用sub时,可以对变量进行不同的设置,也可以将它们设置为默认值。

        4
  •  2
  •   Arpan Saini    4 年前

    您可以在一行中定义和赋值,如下所示。我给出了一个在单行中声明和赋值的两个变量的例子。如果多个变量的数据类型相同

     Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946
    
        5
  •  1
  •   Vadzim    6 年前

    With statement .

    例如,

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

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