Can I simultaneously declare and assign a variable in VBA?

VbaVariable Declaration

Vba Problem Overview


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)

Vba Solutions


Solution 1 - Vba

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;

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

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

Solution 2 - Vba

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

Dim w As New Widget

But not with strings or variants.

Solution 3 - Vba

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

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

Solution 4 - Vba

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.

Solution 5 - Vba

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan R. O'BrienView Question on Stackoverflow
Solution 1 - VbaAlex K.View Answer on Stackoverflow
Solution 2 - VbaJohn M GantView Answer on Stackoverflow
Solution 3 - VbaArpan SainiView Answer on Stackoverflow
Solution 4 - VbaPatrick LepelletierView Answer on Stackoverflow
Solution 5 - VbaVadzimView Answer on Stackoverflow