In Excel VBA, use a variable-length String to hold long text; it can theoretically contain about 2 billion characters, although available memory and Excel’s own limits usually matter first. In particular, a worksheet cell can hold at most 32,767 characters, so a VBA string that is longer than that cannot be saved intact in one cell.
What a long string means in VBA
VBA’s String data type is designed for text. A variable-length string grows or shrinks as you assign different text to it, which makes it the normal choice for messages, imported content, generated reports, and other text whose size is not known in advance. Declare it explicitly so the type and intent are clear:
Dim message As String
A fixed-length string is a different type of declaration: Dim code As String * 12 reserves a fixed character length and pads shorter assignments with spaces. Fixed-length strings are useful for some record formats, but they are generally a poor fit for arbitrary long text. For longer content, use an ordinary variable-length string.
The often-quoted maximum of roughly 2 billion characters is a theoretical data-type limit, not a practical promise that every workbook can hold a string that large. VBA has to keep the string in memory, and Excel’s process architecture, other open workbooks, and the size of the rest of the data all affect what is feasible. A 32-bit Excel process has a more constrained address space than 64-bit Excel. Even on 64-bit Excel, very large strings can consume substantial memory and make a macro slow or unstable.
VBA string limits versus worksheet limits
It is important to distinguish a VBA variable from an Excel cell. The VBA variable can hold much more text than a cell can store. Excel worksheet cells have a limit of 32,767 characters per cell. A long value may therefore exist successfully in VBA but fail to fit when the macro writes it to a worksheet. Do not assume that a cell’s displayed width or the formula bar changes this storage limit.
Excel also has limits on other parts of a workbook, such as formula length and the amount of data a worksheet can contain. Those are separate from the maximum size of a VBA string. If the text originates in a cell, it could already have been limited before VBA reads it; if the macro constructs the text itself, the variable may be longer than any one cell can accept.
Before assigning a potentially long value to a cell, check its length and decide what the workbook should do if it exceeds the cell limit. For example, the macro might stop with a clear message, divide the text among several cells, or save it to a text file. Silently trimming content is rarely a good default because the missing ending can be difficult to notice.
Creating a long string from smaller pieces
Long text is often assembled from shorter pieces: paragraphs, labels, data values, or sections of a generated report. For a known set of pieces, VBA’s Join function is a concise option. The example below combines three pieces with a line break between each one:
Sub BuildLongText()
Dim parts(0 To 2) As String
Dim result As String
' Store each section separately, then combine them.
parts(0) = "First section of the report."
parts(1) = "Second section of the report."
parts(2) = "Final section of the report."
result = Join(parts, vbCrLf)
Debug.Print Len(result)
MsgBox Left$(result, 100)
End Sub
vbCrLf inserts a Windows-style line break. Use vbLf when a line feed alone is appropriate, such as when matching a particular text format. Len returns the string’s character length, while Left$ returns a specified number of characters from its beginning. The dollar sign on string functions indicates a String return type; it is a common VBA convention, not a different way of setting a size limit.
For a collection of pieces created in a loop, you can place them in a string array and join the array after the loop. This can be easier to maintain than one enormous statement containing dozens of concatenations. If the content is naturally generated one section at a time, keep each section in a separate variable or array element until you know how it will be used.
Concatenation and performance
Use the ampersand operator, &, to join text in VBA. Although + can sometimes concatenate strings, it can also perform numeric addition or trigger type conversions. That ambiguity can produce confusing results when a value is empty, numeric, or stored as a Variant. For text, & communicates the intended operation directly.
Repeatedly appending a small piece to a growing string is simple and often perfectly adequate for modest amounts of text. However, each reassignment may require VBA to create a larger string and copy existing content. When a loop creates many thousands of pieces, that repeated copying can become costly. A useful approach is to collect pieces first and combine them once with Join, or to test performance with realistic input sizes rather than assuming the simplest-looking loop will scale.
VBA does not include the .NET StringBuilder class as a built-in VBA type. If you see advice to declare a VBA StringBuilder directly, check what library or external component that advice depends on. For ordinary Excel macros, an array of pieces followed by Join is a straightforward native technique. For very large data, writing or processing it in chunks may be better than keeping every character in one in-memory variable.
Writing long text to a worksheet
Before writing text to a cell, check the length. The following complete macro illustrates the check and writes a short test string only if it is within the cell limit:
Sub WriteTextToCell()
Dim text As String
Dim target As Range
' Replace this sample with the text your macro creates.
text = String$(30000, "x")
Set target = ThisWorkbook.Worksheets("Sheet1").Range("A1")
If Len(text) > 32767 Then
MsgBox "The text is too long for one Excel cell."
Exit Sub
End If
target.Value2 = text
End Sub
This example uses String$ to make a string containing 30,000 copies of the character x, so it is under the cell limit. Change the sample text and worksheet reference to suit the workbook. The macro writes to cell A1, so save a copy of the workbook before running it; macros cannot be undone with Ctrl+Z.
When transferring a range of many values, assigning a two-dimensional array to a same-sized range is often more efficient than writing cells one at a time. That efficiency does not remove the per-cell text limit. If one item is too long, handle it before placing the array into the range.
When text will not fit in one cell
If a value exceeds 32,767 characters, choose a storage layout that preserves all of it. Splitting text into consecutive cells is one option, but make the parts identifiable and keep their order. For example, a separate record ID and sequence number can help a later macro reconstruct each original value. Avoid splitting at arbitrary positions if the text must remain readable; where practical, split at paragraph or line boundaries.
A text file is another option when the content is a document, log, or export rather than a value intended for cell-by-cell analysis. A workbook can store a file path or a shorter summary while the full content remains in the external file. Text files avoid the worksheet cell limit, but they do not make memory unlimited: reading an entire large file into one VBA String still requires memory. For large files, process records or chunks incrementally and consider how encoding and line endings should be preserved.
Putting a long text value into a comment, note, shape, or another workbook object is not automatically a reliable workaround. Those objects have their own behavior and limitations, and they may be harder to search, export, or maintain. Choose the storage method based on what users need to do with the content, not just on where it can be pasted.
Common problems and ways to diagnose them
- The text stops at a cell boundary: Check
Len(text)before assigning the value. The problem may be the worksheet’s 32,767-character limit, not the VBA variable’s capacity. - A long statement is hard to edit: Split the text into named pieces and combine them. VBA supports explicit line continuation with a space followed by an underscore, but there is a limit on how many continuations can be used in one logical statement. Avoid building an entire document as a single continued source line.
- Unexpected spaces appear: Fixed-length strings are padded with spaces. Use a variable-length
Stringunless the fixed-width format is intentional, and inspect the value for leading or trailing spaces. - Text joins incorrectly: Use
&for concatenation and insert separators deliberately. A line break is not added automatically; includevbCrLfor the separator required by the destination format. - The macro becomes slow: Check whether it repeatedly rebuilds a very large string inside a loop. Gather pieces and join them, reduce unnecessary copies, or process the text in chunks.
For debugging, inspect the length and a small excerpt rather than trying to display the entire value in a message box. The Immediate window in the VBA editor can show a length with Debug.Print Len(text). You can also inspect the beginning and ending portions separately to check whether the expected sections were assembled. A string can be correct in memory yet still be truncated or rejected at the point where it is written to a cell or exported.
Choosing the right approach
For a few paragraphs or a modest report, one variable-length String and & or Join are usually enough. For many generated fragments, collect them in an array and join once. For data that must appear in Excel, verify that each cell stays within its limit and define a clear splitting rule. For a large document or log, use a file or another storage system and avoid loading more into memory than the macro needs.
The best choice also depends on the next operation. If users need to filter, sort, or calculate with the content, keep structured values in separate columns rather than combining everything into one giant string. If the content is meant to be read as a document, preserve paragraphs and use a file format suited to documents. A single long string is convenient for processing text as a whole, but it is not always the best way to organize information.
Frequently Asked Questions
What is the maximum length of a VBA String?
A variable-length VBA String has a theoretical capacity of approximately 2 billion characters. Available memory and the Excel process architecture usually impose a much lower practical limit, so that figure should not be treated as a guaranteed working size.
Why can VBA hold text that Excel will not put in a cell?
VBA strings and worksheet cells have different limits. A VBA String can be much longer than 32,767 characters, but a single Excel cell cannot store more than 32,767 characters.
Does VBA have a StringBuilder function?
There is no built-in VBA StringBuilder type equivalent to .NET’s class. For many pieces of text, store the pieces in a string array and combine them with Join; for very large data, consider processing chunks or using a file.
Should I use plus or ampersand to join strings?
Use & for text concatenation. The plus operator can mean numeric addition and may behave unexpectedly when values have different types.
Can I put a 50,000-character string in an Excel cell?
No, not as one cell value. Split it across cells with a reconstruction plan, or store the full text in an external file or another suitable location.
Related
- Excel Merge Cells and Keep All Text Without Data Loss
- Excel Merged Cells: Do They Need to Be the Same Size?
- Excel Merge Cells but Keep All Data?
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Access VBA String to Number: Safe Conversion GuideIn Access VBA, convert a numeric string with the function that matches the number you need: use CLng…
- Excel VBA: Find the First Row Above a Value ThresholdTo find the first row where a cell’s value is greater than a threshold, loop through the relevant…
- Excel VBA Get Array Dimensions: Bounds, Rank, and SizeIn Excel VBA, use LBound(array, dimension) and UBound(array, dimension) to get an array’s lower and upper bounds; its…
- Excel VBA: Copy and Paste Range ValuesTo copy a range’s results without its formulas or formatting, assign the source range’s Value property to a…
- Macro Recorder App: What It Does and How to ChooseA macro recorder app captures a sequence of actions so you can repeat them automatically; in desktop Excel…
- Delete Entire Row VBA: Examples and Safety TipsTo delete a complete worksheet row with VBA, use Rows(rowNumber).Delete on a specifically named worksheet, such as Worksheets("Data").Rows(5).Delete.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.