<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="VB6Parse Library Reference - right - String">
<title>right - String - VB6Parse Library Reference</title>
<link rel="stylesheet" href="../../../assets/css/style.css">
<link rel="stylesheet" href="../../../assets/css/docs-style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<script src="../../../assets/js/theme-switcher.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/vbnet.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<body>
<header class="docs-header">
<div class="container">
<h1><a href="../../../index.html">VB6Parse</a> / <a href="../../../library/index.html">Library</a> / <a href="../../../library/functions/string/index.html">String</a> / right</h1>
<p class="tagline">VB6 Library Reference</p>
</div>
</header>
<nav class="docs-nav">
<div class="container">
<a href="../../../index.html">Home</a>
<a href="../../../library/index.html">Library Reference</a>
<a href="../../../documentation.html">Documentation</a>
<a href="https://docs.rs/vb6parse" target="_blank">API Docs</a>
<a href="https://github.com/scriptandcompile/vb6parse" target="_blank">GitHub</a>
<button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
<span class="theme-icon">🌙</span>
</button>
</div>
</nav>
<main class="container">
<article class="library-item">
<h1 id="right-function">Right Function</h1>
<p>Returns a String containing a specified number of characters from the right side of a string.</p>
<h2 id="syntax">Syntax</h2>
<pre><code class="language-vbnet">Right(string, length)</code></pre>
<h2 id="parameters">Parameters</h2>
<ul>
<li><code>string</code> - Required. String expression from which the rightmost characters are returned.</li>
<li><code>length</code> - Required. Long indicating how many characters to return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in <code>string</code>, the entire string is returned.</li>
</ul>
<h2 id="return-value">Return Value</h2>
<p>Returns a <code>String</code> containing the specified number of characters from the right side of the string.</p>
<h2 id="remarks">Remarks</h2>
<p>The <code>Right</code> function extracts a substring from the end of a string. It is commonly used for:
- Extracting file extensions
- Getting the last N characters of a string
- Parsing fixed-width data from the right
- Removing prefixes or extracting suffixes
<strong>Important Notes</strong>:
- If <code>length</code> is 0, an empty string ("") is returned
- If <code>length</code> >= Len(string), the entire string is returned
- If <code>string</code> is Null, Right returns Null
- If <code>length</code> is negative, a runtime error occurs (Error 5: Invalid procedure call or argument)
- The function is 1-based (counts from position 1, not 0)
<strong>Behavior with Different Length Values</strong>:</p>
<table>
<thead>
<tr>
<th>Length Value</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Empty string ("")</td>
</tr>
<tr>
<td>1 to Len(string)</td>
<td>Rightmost N characters</td>
</tr>
<tr>
<td>> Len(string)</td>
<td>Entire string</td>
</tr>
<tr>
<td>Negative</td>
<td>Runtime error (Error 5)</td>
</tr>
</tbody>
</table>
<h2 id="typical-uses">Typical Uses</h2>
<ol>
<li><strong>File Extensions</strong>: Extract file extension from filename</li>
<li><strong>Data Parsing</strong>: Extract rightmost fields from fixed-width data</li>
<li><strong>String Validation</strong>: Check string endings/suffixes</li>
<li><strong>Number Formatting</strong>: Get last digits of numbers</li>
<li><strong>Path Manipulation</strong>: Extract filename from path</li>
<li><strong>Text Processing</strong>: Remove prefixes, keep suffixes</li>
<li><strong>Data Extraction</strong>: Get trailing characters from codes/IDs</li>
<li><strong>String Truncation</strong>: Keep only the rightmost portion</li>
</ol>
<h2 id="basic-examples">Basic Examples</h2>
<h3 id="example-1-extract-file-extension">Example 1: Extract File Extension</h3>
<pre><code class="language-vbnet">Dim filename As String
Dim extension As String
filename = "document.txt"
extension = Right(filename, 4) ' Returns ".txt"</code></pre>
<h3 id="example-2-get-last-n-characters">Example 2: Get Last N Characters</h3>
<pre><code class="language-vbnet">Dim accountNumber As String
Dim lastFour As String
accountNumber = "1234567890"
lastFour = Right(accountNumber, 4) ' Returns "7890"</code></pre>
<h3 id="example-3-check-string-ending">Example 3: Check String Ending</h3>
<pre><code class="language-vbnet">Dim filename As String
filename = "report.pdf"
If Right(filename, 4) = ".pdf" Then
MsgBox "This is a PDF file"
End If</code></pre>
<h3 id="example-4-extract-from-fixed-width-data">Example 4: Extract from Fixed-Width Data</h3>
<pre><code class="language-vbnet">Dim record As String
Dim zipCode As String
record = "John Doe New York 10001"
zipCode = Right(record, 5) ' Returns "10001"</code></pre>
<h2 id="common-patterns">Common Patterns</h2>
<h3 id="pattern-1-getfileextension">Pattern 1: <code>GetFileExtension</code></h3>
<pre><code class="language-vbnet">Function GetFileExtension(filename As String) As String
' Extract file extension including the dot
Dim dotPos As Integer
dotPos = InStrRev(filename, ".")
If dotPos > 0 Then
GetFileExtension = Right(filename, Len(filename) - dotPos + 1)
Else
GetFileExtension = ""
End If
End Function</code></pre>
<h3 id="pattern-2-getlastnchars">Pattern 2: <code>GetLastNChars</code></h3>
<pre><code class="language-vbnet">Function GetLastNChars(text As String, n As Long) As String
' Safely get last N characters (won't error if string is too short)
If n <= 0 Then
GetLastNChars = ""
ElseIf n >= Len(text) Then
GetLastNChars = text
Else
GetLastNChars = Right(text, n)
End If
End Function</code></pre>
<h3 id="pattern-3-endswithstring">Pattern 3: <code>EndsWithString</code></h3>
<pre><code class="language-vbnet">Function EndsWithString(text As String, suffix As String, _
Optional caseSensitive As Boolean = True) As Boolean
' Check if string ends with a specific suffix
Dim textEnd As String
Dim suffixLen As Long
suffixLen = Len(suffix)
If suffixLen > Len(text) Then
EndsWithString = False
Exit Function
End If
textEnd = Right(text, suffixLen)
If caseSensitive Then
EndsWithString = (textEnd = suffix)
Else
EndsWithString = (UCase(textEnd) = UCase(suffix))
End If
End Function</code></pre>
<h3 id="pattern-4-removeprefix">Pattern 4: <code>RemovePrefix</code></h3>
<pre><code class="language-vbnet">Function RemovePrefix(text As String, prefixLen As Long) As String
' Remove prefix by keeping rightmost characters
If prefixLen >= Len(text) Then
RemovePrefix = ""
Else
RemovePrefix = Right(text, Len(text) - prefixLen)
End If
End Function</code></pre>
<h3 id="pattern-5-padlefttolength">Pattern 5: <code>PadLeftToLength</code></h3>
<pre><code class="language-vbnet">Function PadLeftToLength(text As String, totalLength As Long, _
Optional padChar As String = " ") As String
' Pad string on the left to reach desired length
Dim currentLen As Long
Dim padding As String
currentLen = Len(text)
If currentLen >= totalLength Then
PadLeftToLength = Right(text, totalLength)
Else
padding = String(totalLength - currentLen, padChar)
PadLeftToLength = padding & text
End If
End Function</code></pre>
<h3 id="pattern-6-getfilenamefrompath">Pattern 6: <code>GetFilenameFromPath</code></h3>
<pre><code class="language-vbnet">Function GetFilenameFromPath(fullPath As String) As String
' Extract filename from full path
Dim slashPos As Integer
slashPos = InStrRev(fullPath, "\")
If slashPos > 0 Then
GetFilenameFromPath = Right(fullPath, Len(fullPath) - slashPos)
Else
GetFilenameFromPath = fullPath
End If
End Function</code></pre>
<h3 id="pattern-7-truncateleft">Pattern 7: <code>TruncateLeft</code></h3>
<pre><code class="language-vbnet">Function TruncateLeft(text As String, maxLength As Long, _
Optional ellipsis As String = "...") As String
' Truncate from left, keeping rightmost characters
Dim textLen As Long
textLen = Len(text)
If textLen <= maxLength Then
TruncateLeft = text
Else
TruncateLeft = ellipsis & Right(text, maxLength - Len(ellipsis))
End If
End Function</code></pre>
<h3 id="pattern-8-formataccountnumber">Pattern 8: <code>FormatAccountNumber</code></h3>
<pre><code class="language-vbnet">Function FormatAccountNumber(accountNum As String) As String
' Format account number showing only last 4 digits
Dim lastFour As String
If Len(accountNum) > 4 Then
lastFour = Right(accountNum, 4)
FormatAccountNumber = "****" & lastFour
Else
FormatAccountNumber = accountNum
End If
End Function</code></pre>
<h3 id="pattern-9-extractdomainextension">Pattern 9: <code>ExtractDomainExtension</code></h3>
<pre><code class="language-vbnet">Function ExtractDomainExtension(url As String) As String
' Extract domain extension (.com, .org, etc.)
Dim dotPos As Integer
' Find last dot
dotPos = InStrRev(url, ".")
If dotPos > 0 Then
ExtractDomainExtension = Right(url, Len(url) - dotPos + 1)
Else
ExtractDomainExtension = ""
End If
End Function</code></pre>
<h3 id="pattern-10-gettrailingdigits">Pattern 10: <code>GetTrailingDigits</code></h3>
<pre><code class="language-vbnet">Function GetTrailingDigits(text As String) As String
' Extract trailing numeric characters
Dim i As Integer
Dim digitCount As Integer
digitCount = 0
For i = Len(text) To 1 Step -1
If IsNumeric(Mid(text, i, 1)) Then
digitCount = digitCount + 1
Else
Exit For
End If
Next i
If digitCount > 0 Then
GetTrailingDigits = Right(text, digitCount)
Else
GetTrailingDigits = ""
End If
End Function</code></pre>
<h2 id="advanced-usage">Advanced Usage</h2>
<h3 id="example-1-file-extension-validator">Example 1: File Extension Validator</h3>
<pre><code class="language-vbnet">' Comprehensive file extension validation and management
Class FileExtensionValidator
Private m_validExtensions As Collection
Public Sub Initialize()
Set m_validExtensions = New Collection
End Sub
Public Sub AddValidExtension(extension As String)
Dim ext As String
' Normalize extension (add dot if missing)
If Left(extension, 1) <> "." Then
ext = "." & extension
Else
ext = extension
End If
On Error Resume Next
m_validExtensions.Add ext, UCase(ext)
On Error GoTo 0
End Sub
Public Function IsValidFile(filename As String) As Boolean
Dim ext As String
Dim dotPos As Integer
dotPos = InStrRev(filename, ".")
If dotPos = 0 Then
IsValidFile = False
Exit Function
End If
ext = Right(filename, Len(filename) - dotPos + 1)
On Error Resume Next
Dim temp As String
temp = m_validExtensions(UCase(ext))
IsValidFile = (Err.Number = 0)
On Error GoTo 0
End Function
Public Function GetExtension(filename As String) As String
Dim dotPos As Integer
dotPos = InStrRev(filename, ".")
If dotPos > 0 Then
GetExtension = Right(filename, Len(filename) - dotPos + 1)
Else
GetExtension = ""
End If
End Function
Public Function ChangeExtension(filename As String, newExt As String) As String
Dim dotPos As Integer
Dim baseName As String
Dim ext As String
dotPos = InStrRev(filename, ".")
If dotPos > 0 Then
baseName = Left(filename, dotPos - 1)
Else
baseName = filename
End If
' Normalize new extension
If Left(newExt, 1) <> "." Then
ext = "." & newExt
Else
ext = newExt
End If
ChangeExtension = baseName & ext
End Function
Public Function GetValidExtensions() As String
Dim ext As Variant
Dim result As String
result = ""
For Each ext In m_validExtensions
If result <> "" Then result = result & ", "
result = result & ext
Next ext
GetValidExtensions = result
End Function
End Class</code></pre>
<h3 id="example-2-path-parser-module">Example 2: Path Parser Module</h3>
<pre><code class="language-vbnet">' Parse and manipulate file paths
Module PathParser
Public Function GetFilename(fullPath As String) As String
' Extract filename from full path
Dim slashPos As Integer
slashPos = InStrRev(fullPath, "\")
If slashPos > 0 Then
GetFilename = Right(fullPath, Len(fullPath) - slashPos)
Else
GetFilename = fullPath
End If
End Function
Public Function GetDirectory(fullPath As String) As String
' Extract directory from full path
Dim slashPos As Integer
slashPos = InStrRev(fullPath, "\")
If slashPos > 0 Then
GetDirectory = Left(fullPath, slashPos - 1)
Else
GetDirectory = ""
End If
End Function
Public Function GetFilenameWithoutExtension(fullPath As String) As String
' Get filename without extension
Dim filename As String
Dim dotPos As Integer
filename = GetFilename(fullPath)
dotPos = InStrRev(filename, ".")
If dotPos > 0 Then
GetFilenameWithoutExtension = Left(filename, dotPos - 1)
Else
GetFilenameWithoutExtension = filename
End If
End Function
Public Function GetExtension(fullPath As String) As String
' Get file extension including dot
Dim filename As String
Dim dotPos As Integer
filename = GetFilename(fullPath)
dotPos = InStrRev(filename, ".")
If dotPos > 0 Then
GetExtension = Right(filename, Len(filename) - dotPos + 1)
Else
GetExtension = ""
End If
End Function
Public Function CombinePath(directory As String, filename As String) As String
' Combine directory and filename
If Right(directory, 1) = "\" Then
CombinePath = directory & filename
Else
CombinePath = directory & "\" & filename
End If
End Function
Public Function GetParentDirectory(fullPath As String) As String
' Get parent directory
Dim dir As String
Dim slashPos As Integer
dir = GetDirectory(fullPath)
slashPos = InStrRev(dir, "\")
If slashPos > 0 Then
GetParentDirectory = Left(dir, slashPos - 1)
Else
GetParentDirectory = ""
End If
End Function
End Module</code></pre>
<h3 id="example-3-string-suffix-matcher">Example 3: String Suffix Matcher</h3>
<pre><code class="language-vbnet">' Match and validate string suffixes
Class StringSuffixMatcher
Private m_caseSensitive As Boolean
Public Sub Initialize(Optional caseSensitive As Boolean = True)
m_caseSensitive = caseSensitive
End Sub
Public Function EndsWith(text As String, suffix As String) As Boolean
' Check if string ends with suffix
Dim textEnd As String
Dim suffixLen As Long
suffixLen = Len(suffix)
If suffixLen > Len(text) Then
EndsWith = False
Exit Function
End If
textEnd = Right(text, suffixLen)
If m_caseSensitive Then
EndsWith = (textEnd = suffix)
Else
EndsWith = (UCase(textEnd) = UCase(suffix))
End If
End Function
Public Function EndsWithAny(text As String, suffixes() As String) As Boolean
' Check if string ends with any of the provided suffixes
Dim i As Integer
For i = LBound(suffixes) To UBound(suffixes)
If EndsWith(text, suffixes(i)) Then
EndsWithAny = True
Exit Function
End If
Next i
EndsWithAny = False
End Function
Public Function RemoveSuffix(text As String, suffix As String) As String
' Remove suffix if present
If EndsWith(text, suffix) Then
RemoveSuffix = Left(text, Len(text) - Len(suffix))
Else
RemoveSuffix = text
End If
End Function
Public Function GetMatchingSuffix(text As String, suffixes() As String) As String
' Return the matching suffix, or empty string
Dim i As Integer
For i = LBound(suffixes) To UBound(suffixes)
If EndsWith(text, suffixes(i)) Then
GetMatchingSuffix = suffixes(i)
Exit Function
End If
Next i
GetMatchingSuffix = ""
End Function
Public Function ReplaceSuffix(text As String, oldSuffix As String, _
newSuffix As String) As String
' Replace suffix if present
If EndsWith(text, oldSuffix) Then
ReplaceSuffix = Left(text, Len(text) - Len(oldSuffix)) & newSuffix
Else
ReplaceSuffix = text
End If
End Function
End Class</code></pre>
<h3 id="example-4-account-number-formatter">Example 4: Account Number Formatter</h3>
<pre><code class="language-vbnet">' Format and mask account numbers securely
Class AccountNumberFormatter
Private m_maskChar As String
Private m_visibleDigits As Integer
Public Sub Initialize(Optional maskChar As String = "*", _
Optional visibleDigits As Integer = 4)
m_maskChar = maskChar
m_visibleDigits = visibleDigits
End Sub
Public Function FormatAccountNumber(accountNum As String) As String
' Format account number showing only last N digits
Dim lastDigits As String
Dim maskedLength As Integer
If Len(accountNum) <= m_visibleDigits Then
FormatAccountNumber = accountNum
Exit Function
End If
lastDigits = Right(accountNum, m_visibleDigits)
maskedLength = Len(accountNum) - m_visibleDigits
FormatAccountNumber = String(maskedLength, m_maskChar) & lastDigits
End Function
Public Function FormatWithSpaces(accountNum As String, _
Optional groupSize As Integer = 4) As String
' Format with spaces every N characters
Dim formatted As String
Dim i As Integer
Dim maskedNum As String
maskedNum = FormatAccountNumber(accountNum)
formatted = ""
For i = 1 To Len(maskedNum) Step groupSize
If i > 1 Then formatted = formatted & " "
formatted = formatted & Mid(maskedNum, i, groupSize)
Next i
FormatWithSpaces = formatted
End Function
Public Function GetLastDigits(accountNum As String) As String
' Get only the visible digits
If Len(accountNum) <= m_visibleDigits Then
GetLastDigits = accountNum
Else
GetLastDigits = Right(accountNum, m_visibleDigits)
End If
End Function
Public Function ValidateAccountNumber(accountNum As String, _
minLength As Integer, _
maxLength As Integer) As Boolean
' Validate account number length
Dim numLen As Integer
numLen = Len(accountNum)
ValidateAccountNumber = (numLen >= minLength And numLen <= maxLength)
End Function
Public Sub SetMaskChar(maskChar As String)
m_maskChar = maskChar
End Sub
Public Sub SetVisibleDigits(visibleDigits As Integer)
m_visibleDigits = visibleDigits
End Sub
End Class</code></pre>
<h2 id="error-handling">Error Handling</h2>
<p>The <code>Right</code> function generates runtime errors in specific situations:
<strong>Error 5: Invalid procedure call or argument</strong>
- Occurs when <code>length</code> parameter is negative
<strong>Error 94: Invalid use of Null</strong>
- Occurs when <code>string</code> parameter is Null
Example error handling:</p>
<pre><code class="language-vbnet">On Error Resume Next
result = Right(userInput, charCount)
If Err.Number <> 0 Then
MsgBox "Error extracting characters: " & Err.Description
result = ""
End If
On Error GoTo 0</code></pre>
<p>Best practice for safe usage:</p>
<pre><code class="language-vbnet">Function SafeRight(text As String, length As Long) As String
If IsNull(text) Then
SafeRight = ""
Exit Function
End If
If length < 0 Then
SafeRight = ""
Exit Function
End If
If length = 0 Then
SafeRight = ""
ElseIf length >= Len(text) Then
SafeRight = text
Else
SafeRight = Right(text, length)
End If
End Function</code></pre>
<h2 id="performance-considerations">Performance Considerations</h2>
<ul>
<li><code>Right</code> is a very fast string function</li>
<li>Performance is O(n) where n is the length parameter</li>
<li>More efficient than using Mid to extract from the end</li>
<li>For large strings, consider caching Len(string) if called multiple times</li>
<li>No significant performance difference between Right and string slicing</li>
</ul>
<h2 id="best-practices">Best Practices</h2>
<ol>
<li><strong>Validate Length</strong>: Check that length parameter is valid before calling</li>
<li><strong>Handle Null</strong>: Check for Null strings if data source is uncertain</li>
<li><strong>Use with <code>InStrRev</code></strong>: Combine with <code>InStrRev</code> for finding from right</li>
<li><strong>Document Intent</strong>: Make clear why extracting from right vs left</li>
<li><strong>Consider Edge Cases</strong>: Handle empty strings, length = 0, length > string length</li>
<li><strong>Use for File Extensions</strong>: Preferred method for extracting file extensions</li>
<li><strong>Combine with Trim</strong>: Often useful to Trim before using Right</li>
<li><strong>Cache String Length</strong>: If using Len(string) multiple times, cache it</li>
<li><strong>Avoid Magic Numbers</strong>: Use named constants for length values</li>
<li><strong>Test Boundary Conditions</strong>: Test with length = 0, 1, Len(string), Len(string)+1</li>
</ol>
<h2 id="comparison-with-related-functions">Comparison with Related Functions</h2>
<table>
<thead>
<tr>
<th>Function</th>
<th>Purpose</th>
<th>Parameters</th>
<th>Use Case</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Right</strong></td>
<td>Extract from right</td>
<td><code>(string, length)</code></td>
<td>Get last N characters, file extensions</td>
</tr>
<tr>
<td><strong>Left</strong></td>
<td>Extract from left</td>
<td><code>(string, length)</code></td>
<td>Get first N characters, prefixes</td>
</tr>
<tr>
<td><strong>Mid</strong></td>
<td>Extract from middle</td>
<td><code>(string, start, [length])</code></td>
<td>Get substring from any position</td>
</tr>
<tr>
<td><strong><code>InStrRev</code></strong></td>
<td>Find from right</td>
<td><code>(string, substring)</code></td>
<td>Find position searching from right</td>
</tr>
<tr>
<td><strong>Len</strong></td>
<td>String length</td>
<td><code>(string)</code></td>
<td>Get total length</td>
</tr>
<tr>
<td><strong><code>RTrim</code></strong></td>
<td>Remove right spaces</td>
<td><code>(string)</code></td>
<td>Remove trailing whitespace</td>
</tr>
</tbody>
</table>
<h2 id="platform-and-version-notes">Platform and Version Notes</h2>
<ul>
<li>Available in all versions of VB6 and VBA</li>
<li>Behavior consistent across all platforms</li>
<li>In VB.NET, replaced by String.Substring or string slicing</li>
<li><code>RightB</code> and <code>RightB</code>$ variants exist for byte data</li>
<li>Right$ returns String type, Right returns Variant</li>
</ul>
<h2 id="limitations">Limitations</h2>
<ul>
<li>Cannot use negative length to count from a different position</li>
<li>No built-in way to extract "all but first N" characters (use Len arithmetic)</li>
<li>Raises error on negative length instead of returning empty string</li>
<li>No case-insensitive comparison built-in</li>
<li>No Unicode-aware variant (uses ANSI/DBCS)</li>
</ul>
<h2 id="related-functions">Related Functions</h2>
<ul>
<li><code>Left</code>: Returns characters from the left side of a string</li>
<li><code>Mid</code>: Returns characters from any position in a string</li>
<li><code>InStrRev</code>: Finds position of substring searching from right to left</li>
<li><code>Len</code>: Returns the length of a string</li>
<li><code>RTrim</code>: Removes trailing spaces from a string</li>
<li><code>InStr</code>: Finds position of substring searching from left to right</li>
</ul>
</article>
<div style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border-color);">
<p>
<a href="index.html">← Back to String</a> |
<a href="../index.html">View all functions</a>
</p>
</div>
</main>
<footer>
<div class="container">
<p>© 2024-2026 VB6Parse Contributors. Licensed under the MIT License.</p>
</div>
</footer>
</body>
</html>