In VBA, declare a text variable with Dim variableName As String, such as Dim customerName As String. The Dim statement declares the variable, while As String gives it a type designed to hold text.
What Dim and String Mean in VBA
Dim is a VBA statement for declaring a variable: it tells the program that a named value will be used and what kind of value it can hold. String is the data type for text. Together, Dim message As String creates a variable called message that can hold text such as a name, label, address, or sentence.
Declaring a variable does not put meaningful text into it. A newly declared VBA String starts as a zero-length string, which contains no characters. Assign a value with the equals sign:
Dim message As String
message = "Ready to run"
After that assignment, message contains the text Ready to run. The variable name is yours to choose, but it should describe what the text represents. Names such as invoiceNumber or firstName are easier to understand later than a vague name like x.
String Declaration Syntax and Naming
The standard pattern is Dim name As String. VBA does not distinguish uppercase and lowercase in variable names, so customerName and CustomerName refer to the same identifier. Names cannot contain spaces, and they should not be reserved VBA words. Use an underscore or camel case to make a multiword name readable.
You can declare several variables in one statement, but specify the type for each one. In Dim firstName, lastName As String, only lastName is a String; firstName is a Variant. This is a frequent source of confusing bugs. Prefer separate declarations or write the type after every variable:
Dim firstName As String
Dim lastName As String
Dim city As String
For code with many declarations, put Option Explicit at the top of the module, above procedures. It makes VBA report a compile error if code uses an undeclared variable, which can catch spelling mistakes before they produce incorrect results. In the Visual Basic Editor, you can enable this automatically for new modules through Tools > Options, then select Require Variable Declaration.
Assigning, Reading, and Showing Text
Put text inside straight double quotation marks when assigning a literal. To include a quotation mark inside the text itself, double it. For example, message = "She said ""hello""" stores the text She said "hello". To combine pieces of text, use the ampersand operator, &. It clearly signals concatenation and avoids some of the type-coercion surprises that can arise with the plus sign.
This small Excel macro assigns a String and writes it to the active sheet. Before running a macro, save a copy of the workbook: VBA changes cannot be reversed with Ctrl+Z.
Sub WriteStringExample()
Dim greeting As String
' Save a copy of the workbook before running this macro.
greeting = "Hello, Excel"
ActiveSheet.Range("A1").Value = greeting
End Sub
In Excel for Microsoft 365 on Windows, open the Visual Basic Editor with Alt+F11, insert the code in a standard module, and run the procedure from the editor. On Mac, use Developer > Visual Basic; the keyboard shortcut can depend on the keyboard and function-key settings. Excel for the web does not run VBA macros. To keep VBA in a workbook, save it as an Excel Macro-Enabled Workbook (.xlsm).
Variable-Length and Fixed-Length Strings
A normal declaration such as Dim note As String creates a variable-length String. Its content can change length as you assign different text, so it is the right choice for nearly all ordinary VBA work. A String can contain letters, numbers, punctuation, spaces, and other text characters; declaring it as String does not automatically validate that the content follows a particular format.
VBA also supports fixed-length strings, declared with a length after the type, for example Dim code As String * 8. That variable has a length of eight characters: shorter assigned text is padded with trailing spaces, and longer text is cut to fit. This behavior can be useful when working with a file format or older interface that requires fixed-width fields, but it is usually inconvenient for normal Excel data. If a comparison or output appears to contain unexpected spaces, check whether the variable is fixed-length.
Use Len(text) to get the number of characters in a String. For example, if city contains Oslo, Len(city) returns 4. LenB measures the number of bytes used in the string representation rather than the number of characters; it is not a substitute for Len when you need a character count.
Scope: Where a String Variable Is Available
Where you put a declaration determines how widely the variable can be used. A Dim statement inside a Sub or Function creates a procedure-level variable, available only within that procedure. When the procedure finishes, its ordinary local variable no longer preserves its assigned value for the next call.
A declaration at the top of a module, outside any procedure, is available to procedures in that module. At module level, Dim has private scope; writing Private makes that intention explicit. A variable declared Public in a standard module can be accessed from other modules in the same VBA project. Use the narrowest scope that fits the task: local variables are easier to reason about because unrelated procedures cannot accidentally change them.
If a procedure-level value needs to persist between calls, VBA also has the Static statement. That is a different choice from a normal local Dim variable and should be used only when retaining the previous value is intentional. For most text-processing macros, a regular local String is simpler and safer.
Working with String Values
VBA includes functions and operators for common text tasks. For example, Trim$ removes leading and trailing spaces, Left$ returns characters from the beginning, Mid$ extracts text from a position, and Replace substitutes one piece of text for another. The dollar-sign versions of some functions return a String rather than a Variant, which can make the intended type clearer.
For example, if fullName contains Ada Lovelace , Trim$(fullName) returns Ada Lovelace. If you need to build a value from different types, convert deliberately when useful: CStr converts many values to text. Avoid relying on implicit conversion when the input might be a date, number, error value, or Null, because those values may need special handling before conversion.
String comparisons can be case-sensitive or case-insensitive depending on the module’s comparison setting. By default, VBA uses binary comparison if no Option Compare statement is specified. Option Compare Text requests text comparison for that module. If a macro checks whether two labels match, decide whether capitalization should matter and set or handle comparisons accordingly; do not assume every comparison ignores case.
Using Strings with Excel Cells
Excel’s object model often returns a Variant from a cell, even when the cell appears to contain text. You can assign text to a cell with a statement such as Range("A1").Value = message, as in the macro above. When reading cell contents into a String, check what the cell can contain first. A blank cell, a number, a worksheet error, or a formula result may need different treatment from ordinary text.
For a cell known to contain ordinary text, an assignment such as Dim textValue As String followed by textValue = CStr(Range("A1").Value) makes the conversion explicit. But a cell containing an Excel error value is not ordinary text, and converting it directly can fail. Test for an error value with VBA’s IsError before conversion when errors are possible. Similarly, Null is a special Variant state, not a String value; use IsNull before attempting to convert data that may contain Null.
It also helps to distinguish an empty string from a cell that contains spaces. An empty string has length zero; a string containing three spaces has length three, even though it may look blank on the worksheet. Use Len or trim the text when whitespace should not count as content. Excel cells have their own storage and display constraints, so a VBA String that holds a long value does not mean every worksheet cell can display or store an unlimited amount of text.
Common String Mistakes and How to Avoid Them
- Leaving out
As String: A declaration without an explicit type can create a Variant rather than a String. Declare the intended type so the code is clearer and VBA can handle values consistently. - Assuming every name in a comma-separated declaration gets the type: In VBA,
Dim a, b As Stringdoes not declare both variables as String. Write the type after each name. - Using
+to join text: Use&for concatenation. The plus sign can be interpreted as numeric addition when values are convertible to numbers. - Confusing empty text and a space:
""contains no characters, while" "contains one. This affects comparisons and length checks. - Converting worksheet values without checking them: Excel cells can hold errors and other non-text values. Test for error values and handle possible Nulls before converting.
- Using a fixed-length String unintentionally: A declaration such as
String * 8pads or truncates content. Use the ordinary variable-length form unless a fixed-width requirement is deliberate.
Frequently Asked Questions
What is the correct way to declare a String in VBA?
Use Dim myText As String inside a procedure. Replace myText with a descriptive variable name.
Does a newly declared VBA String contain Null?
No. A normal String variable starts as a zero-length string. Null is a special value associated with Variants, not the initial value of a String variable.
How do I put a String into an Excel cell?
Assign it to a cell’s value, for example Range("A1").Value = myText. Make sure the worksheet and cell are the intended destination, and account for Excel errors or other non-text data when reading values back.
Should I use String or Variant for text?
Use String when the variable is meant to contain text. Use Variant when the value genuinely may have different types or special states, and then check the value before converting or processing it.
Can Excel for the web run VBA?
No. Excel for the web can open a macro-enabled workbook, but VBA macros must be run in the Excel desktop application. On Windows and Mac, macro availability and security settings can affect whether a procedure runs.
Related
- Excel Data Validation Icon: What It Looks Like and Does
- Data Validation Multiple Selection in Excel: What Works
- Data Validation Interview Questions and Strong Answers
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Error Handling: On Error, Err, and RecoveryIn Excel VBA, handle runtime errors with On Error GoTo HandlerLabel, inspect the failure through the Err object,…
- Excel Macro Editor: How to Open and Use the VBA EditorThe Excel macro editor is the Visual Basic Editor (VBE), the built-in environment for viewing, writing, and debugging…
- Excel VBA: Copy a Column and Paste Values Only SafelyTo copy a column in Excel VBA and paste only its values, copy the source column and use…
- Excel VBA: Get the Current Workbook File Path EasilyIn Excel VBA, use ThisWorkbook.Path to get the folder path of the workbook that contains the code, or…
- Excel VBA: Get the Day of the Week from a Date ValueIn Excel VBA, use Weekday to get a date’s weekday number and WeekdayName to turn that number into…
- Excel VBA Worksheet Functions: What You Can UseExcel VBA can call many worksheet functions through Application.WorksheetFunction, including Sum, Average, CountIf, VLookup, Index, Match, Round, Max,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.