VBA Assign String to Variable: Syntax and Examples

VBA & macros · Updated November 18, 2026

To assign text to a VBA variable, declare it as a string with Dim and use the equals sign: message = "Hello". For example, Dim message As String followed by message = "Hello" stores that text in the variable named message.

The basic string assignment pattern

A VBA string variable holds text, such as a name, a message, a code, or a value read from a worksheet cell. The usual pattern has two parts: declare the variable and assign a value to it. Put both statements inside a procedure, such as a Sub or Function. In the Visual Basic Editor, a simple Excel macro looks like this:

Sub AssignText()
    Dim message As String

    ' Store text in the variable.
    message = "Hello from VBA"

    MsgBox message
End Sub

When the macro runs, VBA stores the text between the quotation marks in message, then displays it. The assignment operator is a single equals sign. It means “put the value on the right into the variable on the left”; it is not a comparison in this statement. The variable must be declared before you use it when Option Explicit is enabled, as it should be in most projects.

In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor, then choose Insert > Module to add a standard module. On a Mac, Option+F11 (sometimes Fn+Option+F11, depending on keyboard settings) opens the editor. Save a copy of the workbook before running a macro: VBA changes cannot be undone with Ctrl+Z. Use an Excel Macro-Enabled Workbook (.xlsm) if you need to preserve the macro.

Declare the variable with the String type

Dim declares a variable, and As String specifies that it stores text. A variable name should describe what the text represents, such as customerName, filePath, or statusMessage. Names cannot contain spaces, and they should not be VBA reserved words. Capitalization does not distinguish one variable from another: VBA treats message and Message as the same name.

A string variable can be declared at different scopes. A variable declared inside a procedure with Dim is local to that procedure. A module-level variable is declared near the top of a module, outside any procedure; the choice of declaration keyword affects whether it is available only inside that module or to other modules. For ordinary assignments, local variables are a clear and safe starting point.

Use Option Explicit at the top of each module to make VBA require declarations. If you mistype a variable name, VBA can then flag it instead of silently creating a second, unintended variable. This is especially helpful in longer macros where a misspelling might otherwise produce an empty value or send text to the wrong place.

Option Explicit

Sub SetCustomerName()
    Dim customerName As String

    ' Assign a sample customer name.
    customerName = "Jordan Lee"
    MsgBox customerName
End Sub

A normal VBA String is variable-length, so it can hold different amounts of text as the macro runs. VBA also supports fixed-length strings, declared with a length such as String * 20, but these are specialized: shorter values are padded with spaces and longer values are truncated. For everyday Excel macros, use the ordinary variable-length form.

Put literal text in quotation marks

Text written directly into VBA code is a string literal and must be enclosed in straight double quotation marks. These marks tell VBA where the text begins and ends. For instance, the text assigned below includes a space and punctuation; both are part of the value:

Sub SetStatus()
    Dim statusMessage As String

    ' Assign a literal string.
    statusMessage = "Ready to process."
    MsgBox statusMessage
End Sub

Do not use single quotation marks to surround a string. In VBA, a single quote begins a comment, so a line written as message = 'Hello' will not assign the word Hello. Single quotes can appear inside a double-quoted string, however: message = "That's ready" is valid.

To include a double quotation mark inside the text itself, double it in the VBA source. For example, an assigned message can display the word ready in quotation marks by writing the two quote characters where the embedded quote should appear. This escaping rule is a frequent source of syntax errors when a string contains dialogue, a file format, or a formula.

Sub SetQuotedMessage()
    Dim message As String

    ' Two quote marks inside the literal produce one in the result.
    message = "The answer is ""ready""."
    MsgBox message
End Sub

VBA also provides constants for common control characters. vbCrLf inserts a new line in many Windows text displays, while vbTab inserts a tab. These are useful when building readable messages; whether line breaks display exactly as expected depends on the destination, such as a message box, a cell, or a text file.

Join strings with the ampersand operator

Use the ampersand operator, &, to combine pieces of text. This is called concatenation. It is clearer and generally safer for joining strings than relying on the plus sign, which can also be used in numeric expressions. Add spaces or punctuation explicitly: VBA does not automatically put separators between concatenated values.

Sub BuildGreeting()
    Dim firstName As String
    Dim greeting As String

    ' Join a name and fixed text, including a deliberate space.
    firstName = "Avery"
    greeting = "Hello, " & firstName & "!"
    MsgBox greeting
End Sub

Here, the result is Hello, Avery!. If the space after the comma were missing from the first literal, the result would be Hello,Avery!. For a long expression, you can split the statement across lines with VBA’s line-continuation characters: a space followed by an underscore at the end of the continued line. Keep the ampersand with the expression so the joined parts remain easy to follow.

Values of other types may need conversion before joining. VBA often converts numbers automatically in a concatenation, but relying on implicit conversion can make output format or regional number settings less predictable. Use CStr when you intentionally need a string representation, and format dates or numbers explicitly if the exact displayed form matters. Note that converting an Excel error value or Null with CStr can raise an error; check the value before conversion when it may contain either.

Assign text from cells and other sources

A string does not have to come from a literal. You can assign text returned by a worksheet cell, a function, or a user prompt. For a cell, qualify the worksheet and range so the macro does not depend on whichever sheet happens to be active. The following example reads the displayed cell value into a string variable and then uses it in a message.

Sub ReadCellText()
    Dim customerName As String

    ' Read a value from a specific worksheet cell.
    customerName = ThisWorkbook.Worksheets("Sheet1").Range("A2").Value
    MsgBox "Customer: " & customerName
End Sub

This assumes the workbook contains a sheet named Sheet1 and the relevant text is in cell A2. A cell’s Value may be a number, date, Boolean, error, or blank rather than text. Assigning a value to a string asks VBA to convert it, so consider the source data and the result you want. If a cell might contain an Excel error, test for that before assigning or converting it; a direct conversion can fail.

For a straightforward prompt, VBA’s InputBox function returns text, so its result can be assigned to a string. Its Cancel button returns an empty string, which is also what the user gets by submitting a blank response. If your macro must distinguish Cancel from an intentionally blank answer, use a prompt design that lets you detect cancellation separately rather than treating every empty string as Cancel.

Reading from a cell does not change that cell, and assigning a string variable does not write anything to the worksheet by itself. To send the value back to a cell, assign the variable to a qualified range’s Value property. Treat reading and writing as separate actions in the code so it is clear which cells a macro can change.

Understand assignment, constants, and object variables

VBA uses the same equals sign to assign a value to a string and to many other variable types. The declared type determines what value VBA expects and how it handles conversions. A string variable can be reassigned any number of times; each new assignment replaces its previous contents rather than adding to them. Use & when you want to append or combine text.

If text should never change during a procedure, you can declare a constant with Const rather than a variable. A constant must be given its value when it is declared. This makes fixed labels, filenames, or repeated message text easier to identify and prevents accidental reassignment. Choose a variable when the value needs to be built or updated while the code runs.

A common misconception is that assigning a string requires the Set keyword. It does not. In VBA, Set is used to assign an object reference, such as a reference to a Worksheet or Range object. A string is a value, not an object reference, so assign it with the equals sign alone. Adding Set before a string assignment produces an error.

Common errors and practical fixes

When a string assignment fails or produces unexpected text, check the declaration, the quotation marks, and the value being assigned. Many problems are small syntax or data-type mismatches rather than a special limitation of strings.

  • Variable not defined: Check for a misspelling and confirm that a variable declaration exists. Option Explicit helps identify this at compile time.
  • Expected end of statement or compile error: Look for a missing closing quotation mark, an unescaped quote inside the text, or a misplaced line-continuation underscore.
  • Text is missing spaces: Add spaces inside the string literals or include a separator in the concatenation. The ampersand does not insert one for you.
  • Unexpected blank value: Check whether the source cell is empty, the user submitted a blank prompt, or a different worksheet was referenced than intended.
  • Type mismatch: Check whether the source is an error value, Null, or an unexpected object. Validate or convert the source deliberately instead of assuming it is plain text.
  • Text is cut off or padded: Look for a fixed-length string declaration. Replace it with an ordinary variable-length String if padding or truncation is not intended.

When debugging, step through the procedure with F8 in the Windows Visual Basic Editor and inspect the variable in the Locals window or Immediate window. On a Mac, the editor’s menus can be used to step through code, and shortcut availability can vary with the keyboard configuration. If a macro modifies workbook content, remember that Ctrl+Z will not reverse those VBA changes; save a copy before running it.

Frequently Asked Questions

How do I assign a string to a variable in VBA?
Declare it with Dim variableName As String, then assign text with variableName = "your text". Put the statements inside a Sub or Function.

Do I need to use Set when assigning a string in VBA?
No. Use the equals sign for a string value. Set is for assigning object references, such as worksheet or range objects.

How do I add one string to another in VBA?
Use the ampersand operator to concatenate the values, and include any required spaces or punctuation in the expression. The ampersand combines the text but does not add separators automatically.

How do I put quotation marks inside a VBA string?
Double the quotation mark inside the literal. For example, two consecutive quote characters in the code represent one quote character in the resulting text.

Can a VBA string variable store a number?
It can hold a number converted to text, but it will then be a string rather than a numeric value. Keep values numeric when you need arithmetic, and convert deliberately when you need their text representation.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.