Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBA - lpad() and rpad() implementation with pad character

Status
Not open for further replies.

PhilipDye

Programmer
Aug 23, 2010
1
US
VBA rpad() and lpad() implementations that support specification of a pad character:

Function rpad(ByVal p_string As String, ByVal p_count As Integer, Optional ByVal p_character As String)
Dim v_character As String * 1
Dim v_count As Integer
If (p_count > 0) Then
v_count = p_count
Else
v_count = 0
End If
If (Len(p_string) >= v_count) Then
rpad = p_string
Exit Function
End If
If (Not IsMissing(p_character)) Then
v_character = p_character
Else
v_character = " "
End If
rpad=Left(p_string+String(v_count,v_character),v_count)
End Function

Function lpad(ByVal p_string As String, ByVal p_count As Integer, Optional ByVal p_character As String)
Dim v_character As String * 1
Dim v_count As Integer
If (p_count > 0) Then
v_count = p_count
Else
v_count = 0
End If
If (Len(p_string) >= v_count) Then
lpad = p_string
Exit Function
End If
If (Not IsMissing(p_character)) Then
v_character = Left(p_character, 1)
Else
v_character = " "
End If
lpad=Right(String(v_count,v_character)+p_string,v_count)
End Function

- Philip

 


Philip,

You've posted some functions, without comment. Was there a reason?

With just a little thought, I've created one function that pads either way. What do you think?
Code:
Function PadMe(VAL As String, PLEN As Integer, Optional PDIR As String = "L", Optional PCHR As String = " ") As String
'VAL the value to pad
'PLEN the total length after padding
'PDIR the direction to pad, LEFT is default
'PCHR the pad character, SPACE is default
    Dim iLen As Integer
    
    iLen = Len(VAL)
    
    If iLen >= PLEN Then Exit Function
    
    Select Case PDIR
        Case "L"
            PadMe = String(PLEN - iLen, PCHR) & VAL
        Case "R"
            PadMe = VAL & String(PLEN - iLen, PCHR)
        Case Else
            Exit Function
    End Select
End Function

Skip,

[glasses]Just traded in my old subtlety...
for a NUANCE![tongue]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top