Skip to main content

Writing assignment statements

Assignment statements assign a value or expression to a variable or constant. Assignment statements always include an equal sign (=).

The following example assigns the return value of the InputBox function to the variable.

Sub Question()
    Dim yourName As String
    yourName = InputBox("What is your name?")
    MsgBox "Your name is " & yourName
End Sub

The Let statement is optional and is usually omitted. For example, the preceding assignment statement can be written.

Let yourName = InputBox("What is your name?").

The Set statement is used to assign an object to a variable that has been declared as an object. The Set keyword is required. In the following example, the Set statement assigns a range on Sheet1 to the object variable myCell.

Sub ApplyFormat()
    Dim myCell As Range
    Set myCell = Worksheets("Sheet1").Range("A1")
    With myCell.Font
        .Bold = True
        .Italic = True
    End With
End Sub

Statements that set property values are also assignment statements. The following example sets the Bold property of the Font object for the active cell.

ActiveCell.Font.Bold = True

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>