Any method equivalent to PadLeft/PadRight?

前端 未结 7 1928
春和景丽
春和景丽 2020-12-03 09:23

Just wondering, is there any equivalent in VBA to VB .NET\'s PadLeft and PadRight methods?

As of right now, whenever I want to take a string and make it a fixed leng

7条回答
  •  [愿得一人]
    2020-12-03 10:00

    Merging the top two answers (thanks to LittleBobbyTables and Brad) and noting the helper function max, I would suggest:

    Function PadLeft(ByVal text As Variant, ByVal totalLength As Integer, ByVal padCharacter As String) As String
        PadLeft = Right(String(totalLength, padCharacter) & CStr(text), max(totalLength, Len(CStr(text))))
    End Function
    
    Function PadRight(ByVal text As Variant, ByVal totalLength As Integer, ByVal padCharacter As String) As String
        PadRight = Left(CStr(text) & String(totalLength, padCharacter), max(totalLength, Len(CStr(text))))
    End Function
    
    Public Function max(ByVal x As Variant, ByVal y As Variant) As Variant
      max = IIf(x > y, x, y)
    End Function
    

    totalLength might be better named minimumLength, since the entire original string is always returned, possibly causing the result to be longer than minimumLength.

提交回复
热议问题