Left in VBA refers to the Left function, which extracts a specified number of characters from the beginning (left side) of a string. For example, Left("Hello", 2) returns "He". It is one of the most commonly used string functions in VBA for Excel, Access, and other Office applications.
What the Left Function Does
The Left function returns a Variant (or String if declared) containing the first n characters of a string. Its syntax is:
Left(string, length)
- string – the text you want to extract from (required).
- length – the number of characters to return (required). If this is 0, an empty string is returned. If it is greater than the length of the string, the entire string is returned.
For example, if cell A1 contains “Invoice #12345”, then Left(Range("A1").Value, 7) returns “Invoice”. The function is case-sensitive only in the sense that it preserves the original case; it does not perform any comparison.
How to Use Left in VBA Code
You can use Left anywhere in a VBA macro. Here is a simple subroutine that extracts the first three characters from a cell and writes them to another cell:
Sub ExtractLeft()
Dim inputText As String
Dim result As String
' Read the value from cell A1
inputText = Range("A1").Value
' Get the first 3 characters
result = Left(inputText, 3)
' Write result to B1
Range("B1").Value = result
End Sub
Before running any macro, save a copy of your workbook because macros cannot be undone with Ctrl+Z. To run the macro, press Alt+F8 (on Mac: Fn+Option+F8), select ExtractLeft, and click Run.
Common Use Cases and Examples
The Left function is useful whenever you need to parse text. Typical scenarios include:
- Extracting area codes from phone numbers:
Left(phone, 3)if the number starts with the area code. - Getting the year from a date string like “2024-05-01”:
Left(dateStr, 4). - Trimming a fixed-width prefix from a product code:
Left(code, 5)to get the category part. - Checking if a string starts with a certain pattern:
If Left(text, 3) = "Mr." Then ...
Here is a more complete example that loops through a column and extracts the first word (up to the first space) from each cell:
Sub ExtractFirstWord()
Dim rng As Range
Dim cell As Range
Dim spacePos As Integer
' Set range to A1:A10
Set rng = Range("A1:A10")
For Each cell In rng
' Find the position of the first space (if any)
spacePos = InStr(cell.Value, " ")
If spacePos > 0 Then
' Extract characters before the first space
cell.Offset(0, 1).Value = Left(cell.Value, spacePos - 1)
Else
' No space, take the whole string
cell.Offset(0, 1).Value = cell.Value
End If
Next cell
End Sub
Note that InStr returns 0 if no space is found, so the If handles that case.
Left vs. Left$ vs. LeftB
VBA provides three related functions that behave slightly differently:
- Left – returns a
Variant. If the string isNull, it returnsNull. This is the version most people use. - Left$ – returns a
Stringand is slightly faster because it avoids the overhead of a Variant. Use it when you are certain the input is a string and notNull. - LeftB – operates on byte data, not characters. It is intended for use with double-byte character sets (DBCS) like some Asian languages. For most modern applications, you should use
Leftbecause it handles Unicode correctly.LeftBcounts bytes, so a character that takes two bytes would be split incorrectly if you use it on regular text.
In practice, Left is the safest and most readable choice. The $ version is a minor optimization that rarely matters unless you are processing huge strings in a loop.
Common Errors and How to Avoid Them
There are a few pitfalls you might encounter when using Left:
- Null values: If the string is
Null,LeftreturnsNull, which can cause a type mismatch if you assign it to aStringvariable. Check forIsNullfirst or useNzin Access. - Length as 0: Returns an empty string, which is usually fine, but if you expect at least one character, handle it explicitly.
- Length greater than string length: Returns the entire string, which is often what you want, but be aware it does not raise an error.
- Non-string input: If you pass a number, VBA converts it to a string automatically. For example,
Left(12345, 2)returns “12”. This can be useful but also surprising if you forget. - Using Left on a cell that contains a number formatted with commas: The value is the raw number, not the formatted display. Use
Range("A1").Textif you need the displayed text.
If you get a “Type Mismatch” error, check that the first argument is not Null and that the second argument is a numeric value (not a text string like “3”).
Alternatives to Left in VBA
Depending on what you need, other functions might be more appropriate:
- Right – extracts characters from the end of a string. Use
Right(text, 4)to get the last four characters. - Mid – extracts a substring starting at a specified position. For example,
Mid(text, 3, 5)returns five characters starting at the third character. - InStr – finds the position of a substring, often used with
Leftto extract up to a delimiter. - Split – splits a string into an array based on a delimiter. For example,
Split("John Doe", " ")(0)returns “John”. This is often easier than usingLeftwithInStr. - Replace – removes or substitutes parts of a string.
For example, to get the first name from a full name, you could use Split(fullName, " ")(0) instead of Left(fullName, InStr(fullName, " ") - 1). The Split approach is cleaner and handles cases where there is no space (the entire string is returned as the first element).
Frequently Asked Questions
Can I use Left on a cell that contains a number?
Yes, VBA converts the number to a string before applying Left. For example, Left(12345, 2) returns “12”. The result is a string, so if you need to use it in arithmetic, convert it back with Val or CLng.
What is the difference between Left and Left$?
Left returns a Variant and can handle Null values (returning Null). Left$ returns a String and is faster, but it will raise an error if the input is Null. In most cases, you can use either; Left is more forgiving.
Does Left work with Unicode characters like emojis?
Yes, Left counts characters, not bytes, so it works correctly with Unicode text, including emojis and accented characters. Do not use LeftB for such text, as it counts bytes and will split multi-byte characters.
How do I extract text after a specific character?
Use Mid combined with InStr. For example, to get everything after the first space: Mid(text, InStr(text, " ") + 1). Or use Split(text, " ")(1) if there is exactly one space.
Why does Left return an empty string when length is 0?
That is the defined behavior. If you pass 0, you get an empty string. This can be useful for conditional logic, but if you expect at least one character, check the length before calling Left.
Performance and Best Practices
For most tasks, Left is fast enough. However, if you are processing thousands of strings in a loop, consider these tips:
- Use
Left$instead ofLeftto avoid Variant overhead. - Assign the string to a variable once instead of calling
Range().Valuerepeatedly. - If you are extracting a fixed number of characters from every cell, consider using the worksheet function
LEFTin a formula instead of VBA, as it is often more efficient for simple tasks. - Always declare your variables with explicit types (
Dim s As String) to improve performance and avoid type conversion errors.
Remember that VBA macros cannot be undone, so always test on a copy of your workbook first.
Related
- Shortcut for File Explorer: Best Ways to Open It Fast
- Tableau String to Number Conversion: The 3 Best Ways
- Data Entry How to Do: Steps, Tools, and Accuracy Tips
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Dictionary: How It Works and When to Use ItYes, Excel VBA can use a Dictionary on Windows, but VBA does not include a native Dictionary type.…
- VBA For Each: Loop Through Collections & RangesThe For Each...Next loop in VBA is the fastest way to repeat a block of code for every…
- Excel VBA If Statements: Syntax, Examples, and TipsIn Excel VBA, an If statement runs code only when a condition is true; use ElseIf for additional…
- VBA Convert Range to Number: 4 WaysTo convert a range of text-formatted numbers to actual numeric values in Excel VBA, use the Value property…
- Excel VBA Delete Whole Row: Safe Methods and ExamplesTo delete an entire worksheet row with VBA, use Rows(row_number).Delete, such as Rows(5).Delete for row 5. In a…
- Excel VBA Goto Statement: Syntax, Risks, and AlternativesThe Excel VBA Goto statement jumps execution to a labeled line within the same procedure. It is a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.