[vba] Can I simultaneously declare and assign a variable in VBA?

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

Dim clientToTest As String
clientToTest = clientsToTest(i)

or

Dim clientString As Variant
clientString = Split(clientToTest)

This question is related to vba variable-declaration

The answer is


You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

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.


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

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

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

Dim w As New Widget

But not with strings or variants.