VB6 StrConv Function
The StrConv function converts a string to a specified format.
Syntax
StrConv(string, conversion[, LCID])
Parameters
string: Required. String expression to be converted.conversion: Required. Integer specifying the type of conversion to perform. Can be one or more of the following constants (combined with+orOr):vbUpperCase(1): Converts the string to uppercase charactersvbLowerCase(2): Converts the string to lowercase charactersvbProperCase(3): Converts the first letter of every word to uppercasevbWide(4): Converts narrow (single-byte) characters to wide (double-byte) charactersvbNarrow(8): Converts wide (double-byte) characters to narrow (single-byte) charactersvbKatakana(16): Converts Hiragana characters to Katakana characters (Japanese)vbHiragana(32): Converts Katakana characters to Hiragana characters (Japanese)vbUnicode(64): Converts the string to Unicode using the default code pagevbFromUnicode(128): Converts the string from Unicode to the default code pageLCID: Optional.LocaleIDvalue, if different from the systemLocaleIDvalue. Default is the systemLocaleID.
Returns
Returns a Variant (String) containing the converted string, or a Variant (Byte array) when converting to/from Unicode.
Remarks
The StrConv function provides powerful string transformation capabilities:
- Case conversion:
vbUpperCase,vbLowerCase, andvbProperCasefor text normalization - Proper case rules:
vbProperCasecapitalizes first letter after spaces and certain punctuation - Wide/Narrow conversion: For Asian languages with double-byte character sets (DBCS)
- Japanese character conversion:
vbKatakanaandvbHiraganafor Japanese text - Unicode conversion:
vbUnicodeconverts string to byte array,vbFromUnicodeconverts byte array to string - Combining conversions: Can combine multiple conversions using
+orOr(e.g.,vbUpperCase + vbWide) - Return type varies: String conversions return String, Unicode conversions return Byte array
- Locale-aware: Proper case conversion respects locale settings
- Performance: Efficient for bulk text transformation
Case Conversion Details
vbUpperCase: Converts all characters to uppercase using locale rulesvbLowerCase: Converts all characters to lowercase using locale rulesvbProperCase: Capitalizes first letter of each word, converts rest to lowercase- Words are delimited by spaces, tabs, and some punctuation
- Preserves existing spacing and punctuation
Unicode Conversion Details
vbUnicode: Converts String to Byte array containing Unicode (UTF-16LE) representation- Each character becomes 2 bytes
- Useful for binary file operations or API calls
vbFromUnicode: Converts Byte array back to String- Expects byte array in Unicode format
- Reverses
vbUnicodeconversion
Wide/Narrow Conversion (DBCS)
- Relevant for Asian languages (Japanese, Chinese, Korean)
- Wide characters occupy two bytes, narrow characters occupy one byte
vbWide: Converts half-width to full-width charactersvbNarrow: Converts full-width to half-width characters
Typical Uses
- Text Normalization: Convert user input to consistent case for comparisons
- Title Formatting: Format text in proper case for titles and headings
- Data Validation: Normalize strings before validation or storage
- Case-Insensitive Operations: Convert to uppercase/lowercase for comparisons
- Unicode File I/O: Convert strings to/from Unicode byte arrays for file operations
- API Calls: Convert strings to Unicode byte arrays for Win32 API calls
- Japanese Text Processing: Convert between Hiragana and Katakana
- Database Storage: Normalize case before storing in databases
Basic Examples
Example 1: Case Conversion
Dim text As String
Dim result As String
text = "Hello World"
result = StrConv(text, vbUpperCase) ' "HELLO WORLD"
result = StrConv(text, vbLowerCase) ' "hello world"
result = StrConv(text, vbProperCase) ' "Hello World"
text = "the quick brown fox"
result = StrConv(text, vbProperCase) ' "The Quick Brown Fox"
Example 2: Unicode Conversion
Dim text As String
Dim bytes() As Byte
Dim restored As String
text = "Hello"
' Convert to Unicode byte array
bytes = StrConv(text, vbUnicode)
' bytes contains: 72, 0, 101, 0, 108, 0, 108, 0, 111, 0
' Convert back to string
restored = StrConv(bytes, vbFromUnicode) ' "Hello"
Example 3: Combining Conversions
Dim text As String
Dim result As String
text = "hello"
' Combine uppercase with wide conversion (for DBCS)
result = StrConv(text, vbUpperCase + vbWide)
Example 4: Proper Case Formatting
Dim name As String
Dim formatted As String
name = "JOHN Q. PUBLIC"
formatted = StrConv(name, vbProperCase) ' "John Q. Public"
name = "o'brien"
formatted = StrConv(name, vbProperCase) ' "O'brien"
' Note: StrConv doesn't handle special cases like O'Brien
Common Patterns
Pattern 1: Normalize User Input
Function NormalizeInput(userInput As String) As String
' Convert to uppercase for case-insensitive processing
NormalizeInput = StrConv(Trim$(userInput), vbUpperCase)
End Function
Pattern 2: Format Name Properly
Function FormatName(name As String) As String
' Convert to proper case for display
FormatName = StrConv(Trim$(name), vbProperCase)
End Function
Pattern 3: Case-Insensitive Comparison
Function EqualsIgnoreCase(str1 As String, str2 As String) As Boolean
EqualsIgnoreCase = (StrConv(str1, vbUpperCase) = StrConv(str2, vbUpperCase))
End Function
Pattern 4: Write Unicode File
Sub WriteUnicodeFile(filename As String, text As String)
Dim fileNum As Integer
Dim bytes() As Byte
bytes = StrConv(text, vbUnicode)
fileNum = FreeFile
Open filename For Binary As #fileNum
Put #fileNum, , bytes
Close #fileNum
End Sub
Pattern 5: Read Unicode File
Function ReadUnicodeFile(filename As String) As String
Dim fileNum As Integer
Dim bytes() As Byte
Dim fileSize As Long
fileNum = FreeFile
Open filename For Binary As #fileNum
fileSize = LOF(fileNum)
ReDim bytes(0 To fileSize - 1)
Get #fileNum, , bytes
Close #fileNum
ReadUnicodeFile = StrConv(bytes, vbFromUnicode)
End Function
Pattern 6: Convert Array of Strings
Sub ConvertArrayToUpperCase(arr() As String)
Dim i As Integer
For i = LBound(arr) To UBound(arr)
arr(i) = StrConv(arr(i), vbUpperCase)
Next i
End Sub
Pattern 7: Title Case for Sentences
Function FormatTitle(title As String) As String
Dim result As String
' Convert to proper case
result = StrConv(title, vbProperCase)
' Handle articles and prepositions (simplified)
result = Replace(result, " A ", " a ")
result = Replace(result, " An ", " an ")
result = Replace(result, " The ", " the ")
result = Replace(result, " Of ", " of ")
result = Replace(result, " In ", " in ")
FormatTitle = result
End Function
Pattern 8: Database Normalization
Function NormalizeForDatabase(value As String) As String
' Trim and convert to uppercase for storage
NormalizeForDatabase = StrConv(Trim$(value), vbUpperCase)
End Function
Pattern 9: Compare with Wildcard
Function MatchesPattern(text As String, pattern As String) As Boolean
' Case-insensitive pattern matching
MatchesPattern = (StrConv(text, vbUpperCase) Like StrConv(pattern, vbUpperCase))
End Function
Pattern 10: Extract Unicode Bytes
Function GetUnicodeBytes(text As String) As String
Dim bytes() As Byte
Dim i As Integer
Dim result As String
bytes = StrConv(text, vbUnicode)
result = ""
For i = LBound(bytes) To UBound(bytes)
result = result & CStr(bytes(i)) & " "
Next i
GetUnicodeBytes = Trim$(result)
End Function
Advanced Usage
Example 1: Text Normalizer Class
' Class: TextNormalizer
' Provides text normalization and conversion utilities
Option Explicit
Public Enum NormalizationMode
UpperCase = 1
LowerCase = 2
ProperCase = 3
NoChange = 0
End Enum
Private m_Mode As NormalizationMode
Private m_TrimSpaces As Boolean
Public Sub Initialize(mode As NormalizationMode, trimSpaces As Boolean)
m_Mode = mode
m_TrimSpaces = trimSpaces
End Sub
Public Function Normalize(text As String) As String
Dim result As String
result = text
' Trim if requested
If m_TrimSpaces Then
result = Trim$(result)
End If
' Apply case conversion
Select Case m_Mode
Case UpperCase
result = StrConv(result, vbUpperCase)
Case LowerCase
result = StrConv(result, vbLowerCase)
Case ProperCase
result = StrConv(result, vbProperCase)
End Select
Normalize = result
End Function
Public Function NormalizeArray(arr() As String) As String()
Dim result() As String
Dim i As Integer
ReDim result(LBound(arr) To UBound(arr))
For i = LBound(arr) To UBound(arr)
result(i) = Normalize(arr(i))
Next i
NormalizeArray = result
End Function
Public Function NormalizeCollection(col As Collection) As Collection
Dim result As New Collection
Dim item As Variant
For Each item In col
result.Add Normalize(CStr(item))
Next item
Set NormalizeCollection = result
End Function
Example 2: Unicode File Handler
' Class: UnicodeFileHandler
' Handles reading and writing Unicode text files
Option Explicit
Public Sub WriteFile(filename As String, text As String, Optional appendMode As Boolean = False)
Dim fileNum As Integer
Dim bytes() As Byte
Dim existingBytes() As Byte
Dim existingSize As Long
Dim newSize As Long
bytes = StrConv(text, vbUnicode)
fileNum = FreeFile
If appendMode And Dir(filename) <> "" Then
' Read existing content
Open filename For Binary As #fileNum
existingSize = LOF(fileNum)
If existingSize > 0 Then
ReDim existingBytes(0 To existingSize - 1)
Get #fileNum, , existingBytes
End If
Close #fileNum
' Combine existing and new bytes
newSize = existingSize + UBound(bytes) + 1
ReDim Preserve existingBytes(0 To newSize - 1)
Dim i As Long
For i = 0 To UBound(bytes)
existingBytes(existingSize + i) = bytes(i)
Next i
bytes = existingBytes
End If
' Write to file
Open filename For Binary As #fileNum
Put #fileNum, , bytes
Close #fileNum
End Sub
Public Function ReadFile(filename As String) As String
Dim fileNum As Integer
Dim bytes() As Byte
Dim fileSize As Long
If Dir(filename) = "" Then
Err.Raise 53, , "File not found"
End If
fileNum = FreeFile
Open filename For Binary As #fileNum
fileSize = LOF(fileNum)
If fileSize = 0 Then
Close #fileNum
ReadFile = ""
Exit Function
End If
ReDim bytes(0 To fileSize - 1)
Get #fileNum, , bytes
Close #fileNum
ReadFile = StrConv(bytes, vbFromUnicode)
End Function
Public Function ReadLines(filename As String) As String()
Dim content As String
Dim lines() As String
content = ReadFile(filename)
lines = Split(content, vbCrLf)
ReadLines = lines
End Function
Public Sub WriteLines(filename As String, lines() As String)
Dim content As String
content = Join(lines, vbCrLf)
WriteFile filename, content
End Sub
Example 3: Case Converter Module
' Module: CaseConverter
' Utilities for case conversion and formatting
Option Explicit
Public Function ToUpper(text As String) As String
ToUpper = StrConv(text, vbUpperCase)
End Function
Public Function ToLower(text As String) As String
ToLower = StrConv(text, vbLowerCase)
End Function
Public Function ToProper(text As String) As String
ToProper = StrConv(text, vbProperCase)
End Function
Public Function ToTitleCase(text As String) As String
' More sophisticated title case
Dim result As String
Dim words() As String
Dim i As Integer
Dim lowercaseWords As String
' Start with proper case
result = StrConv(text, vbProperCase)
' Lowercase certain words (not first word)
lowercaseWords = " a an the and but or for nor of in on at to from by "
words = Split(result, " ")
For i = 1 To UBound(words) ' Start at 1 to skip first word
If InStr(lowercaseWords, " " & LCase$(words(i)) & " ") > 0 Then
words(i) = LCase$(words(i))
End If
Next i
ToTitleCase = Join(words, " ")
End Function
Public Function ToggleCase(text As String) As String
' Toggle case of each character
Dim i As Integer
Dim char As String
Dim result As String
result = ""
For i = 1 To Len(text)
char = Mid$(text, i, 1)
If char = UCase$(char) Then
result = result & LCase$(char)
Else
result = result & UCase$(char)
End If
Next i
ToggleCase = result
End Function
Public Function IsAllUpper(text As String) As Boolean
IsAllUpper = (text = StrConv(text, vbUpperCase))
End Function
Public Function IsAllLower(text As String) As Boolean
IsAllLower = (text = StrConv(text, vbLowerCase))
End Function
Public Function IsProperCase(text As String) As Boolean
IsProperCase = (text = StrConv(text, vbProperCase))
End Function
Example 4: String Comparison Helper
' Module: StringComparisonHelper
' Case-insensitive comparison utilities
Option Explicit
Public Function EqualsIgnoreCase(str1 As String, str2 As String) As Boolean
EqualsIgnoreCase = (StrConv(str1, vbUpperCase) = StrConv(str2, vbUpperCase))
End Function
Public Function StartsWithIgnoreCase(text As String, prefix As String) As Boolean
Dim textUpper As String
Dim prefixUpper As String
textUpper = StrConv(text, vbUpperCase)
prefixUpper = StrConv(prefix, vbUpperCase)
StartsWithIgnoreCase = (Left$(textUpper, Len(prefixUpper)) = prefixUpper)
End Function
Public Function EndsWithIgnoreCase(text As String, suffix As String) As Boolean
Dim textUpper As String
Dim suffixUpper As String
textUpper = StrConv(text, vbUpperCase)
suffixUpper = StrConv(suffix, vbUpperCase)
EndsWithIgnoreCase = (Right$(textUpper, Len(suffixUpper)) = suffixUpper)
End Function
Public Function ContainsIgnoreCase(text As String, searchValue As String) As Boolean
Dim textUpper As String
Dim searchUpper As String
textUpper = StrConv(text, vbUpperCase)
searchUpper = StrConv(searchValue, vbUpperCase)
ContainsIgnoreCase = (InStr(textUpper, searchUpper) > 0)
End Function
Public Function IndexOfIgnoreCase(text As String, searchValue As String) As Long
Dim textUpper As String
Dim searchUpper As String
textUpper = StrConv(text, vbUpperCase)
searchUpper = StrConv(searchValue, vbUpperCase)
IndexOfIgnoreCase = InStr(textUpper, searchUpper)
End Function
Public Function ReplaceIgnoreCase(text As String, findText As String, _
replaceText As String) As String
Dim result As String
Dim pos As Long
Dim lastPos As Long
Dim textUpper As String
Dim findUpper As String
result = ""
lastPos = 1
textUpper = StrConv(text, vbUpperCase)
findUpper = StrConv(findText, vbUpperCase)
pos = InStr(lastPos, textUpper, findUpper)
Do While pos > 0
result = result & Mid$(text, lastPos, pos - lastPos) & replaceText
lastPos = pos + Len(findText)
pos = InStr(lastPos, textUpper, findUpper)
Loop
result = result & Mid$(text, lastPos)
ReplaceIgnoreCase = result
End Function
Error Handling
The StrConv function can raise the following errors:
- Error 5 (Invalid procedure call or argument): If
conversionconstant is invalid or incompatible combinations are used - Error 13 (Type mismatch): If
stringargument cannot be converted to a string - Error 6 (Overflow): In rare cases with very large strings or byte arrays
Performance Notes
- Very fast for case conversions (uppercase, lowercase, proper case)
- Unicode conversions are efficient but create byte arrays (memory overhead)
- Proper case conversion slower than upper/lower case (more complex rules)
- Wide/Narrow conversions only relevant for DBCS environments
- Consider caching converted values if used repeatedly
- For simple uppercase/lowercase,
UCase$andLCase$may be slightly faster
Best Practices
- Use for normalization before comparisons or storage
- Combine with Trim$ to remove leading/trailing spaces before conversion
- Handle proper case limitations - doesn't handle special cases like "O'Brien" or "
McDonald" - Cache conversion constants in variables for clarity (e.g.,
Const UPPER_CASE = vbUpperCase) - Use Unicode conversion for binary file I/O or API calls requiring Unicode
- Test with locale-specific text when using proper case or locale-dependent conversions
- Document conversion type in comments when not obvious from context
- Consider alternatives -
UCase$,LCase$for simple case conversion (slightly faster) - Validate conversion parameter when accepting user input
- Handle byte array return appropriately when using
vbUnicodeconversion
Comparison Table
| Function | Purpose | Returns | Locale-Aware |
|---|---|---|---|
StrConv |
Multiple conversions | String or Byte array | Yes |
UCase$ |
Uppercase only | String | Yes |
LCase$ |
Lowercase only | String | Yes |
Format$ |
General formatting | String | Yes |
Platform Notes
- Available in VB6 and VBA
- Not available in
VBScript vbWide/vbNarrowprimarily for Asian language environmentsvbKatakana/vbHiraganaonly meaningful for Japanese text- Unicode conversion uses UTF-16LE (Windows default)
- Proper case rules may vary by locale
- LCID parameter rarely used (defaults to system locale)
Limitations
- Proper case doesn't handle special cases (O'Brien,
McDonald, etc.) - Cannot specify custom word delimiters for proper case
- Unicode conversion always uses UTF-16LE (cannot specify encoding)
- No direct support for other Unicode formats (UTF-8, UTF-32)
- Wide/Narrow conversion limited to DBCS environments
- Cannot combine incompatible conversions (e.g.,
vbUpperCase + vbLowerCase) - No validation of byte array format when using
vbFromUnicode - LCID parameter has limited practical use