VB6Parse / Library / String / strconv

VB6 Library Reference

VB6 StrConv Function The StrConv function converts a string to a specified format.

Syntax

StrConv(string, conversion[, LCID])

Parameters

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, and vbProperCase for text normalization - Proper case rules: vbProperCase capitalizes first letter after spaces and certain punctuation - Wide/Narrow conversion: For Asian languages with double-byte character sets (DBCS) - Japanese character conversion: vbKatakana and vbHiragana for Japanese text - Unicode conversion: vbUnicode converts string to byte array, vbFromUnicode converts byte array to string - Combining conversions: Can combine multiple conversions using + or Or (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

Unicode Conversion Details

Wide/Narrow Conversion (DBCS)

Typical Uses

  1. Text Normalization: Convert user input to consistent case for comparisons
  2. Title Formatting: Format text in proper case for titles and headings
  3. Data Validation: Normalize strings before validation or storage
  4. Case-Insensitive Operations: Convert to uppercase/lowercase for comparisons
  5. Unicode File I/O: Convert strings to/from Unicode byte arrays for file operations
  6. API Calls: Convert strings to Unicode byte arrays for Win32 API calls
  7. Japanese Text Processing: Convert between Hiragana and Katakana
  8. 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 conversion constant is invalid or incompatible combinations are used - Error 13 (Type mismatch): If string argument cannot be converted to a string - Error 6 (Overflow): In rare cases with very large strings or byte arrays

Performance Notes

Best Practices

  1. Use for normalization before comparisons or storage
  2. Combine with Trim$ to remove leading/trailing spaces before conversion
  3. Handle proper case limitations - doesn't handle special cases like "O'Brien" or "McDonald"
  4. Cache conversion constants in variables for clarity (e.g., Const UPPER_CASE = vbUpperCase)
  5. Use Unicode conversion for binary file I/O or API calls requiring Unicode
  6. Test with locale-specific text when using proper case or locale-dependent conversions
  7. Document conversion type in comments when not obvious from context
  8. Consider alternatives - UCase$, LCase$ for simple case conversion (slightly faster)
  9. Validate conversion parameter when accepting user input
  10. Handle byte array return appropriately when using vbUnicode conversion

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

Limitations

← Back to String | View all functions