46

只是想知道,VBA 中是否有与 VB .NET 的 PadLeft 和 PadRight 方法等效的方法?

截至目前,每当我想获取一个字符串并将其设置为带有前导空格的固定长度时,我都会根据字符串的长度执行 For...Next 循环。

例如,我将使用以下代码将字符串格式化为 8 个字符并带有前导空格:

intOrdNoLen = Len(strOrdNo)
For i = 1 To (8 - intOrdNoLen) Step 1
    strOrdNo = " " & strOrdNo
Next

有没有办法在 VBA 中用更少的行来做同样的事情?

4

8 回答 8

82

我不相信有任何明确的PADLEFTorPADRIGHT函数,但是您可以使用SPACEand LEFTor的组合RIGHT在您的字符串前面加上空格,然后获取正确的 X 个字符。

桨叶

strOrdNo = RIGHT(Space(8) & strOrdNo, 8)

如果您想要一个字符而不是空格,您可以使用STRING而不是空格(下面的示例左填充 X):

strOrdNo = RIGHT(String(8, "X") & strOrdNo, 8)

焊盘

strOrdNo = LEFT(strOrdNo & Space(8), 8)

strOrdNo = LEFT(strOrdNo & String(8, "X"), 8)
于 2012-08-21T17:56:11.290 回答
17

你可以使用这些。将它们放在公共模块中

'NB 如果输入字符串长于总长度则失​​败

Function PadLeft(text As Variant, totalLength As Integer, padCharacter As String) As String
    PadLeft = String(totalLength - Len(CStr(text)), padCharacter) & CStr(text)
End Function

Function PadRight(text As Variant, totalLength As Integer, padCharacter As String) As String
    PadRight = CStr(text) & String(totalLength - Len(CStr(text)), padCharacter)
End Function
于 2012-08-21T17:58:54.573 回答
8

由于我们通常在左侧填充,因此 Format() 函数更短、更简单:

Format(number, "    ")

Format(number, "00")
于 2014-12-20T13:19:13.393 回答
7
Format("abc","!@@@@@@") ' width >= 6; pad right side with spaces
Format("abc","@@@@@@") ' width >= 6; pad left side with spaces
于 2017-02-08T03:53:42.667 回答
3

您还可以在 VBA 中使用固定长度的字符串:

Dim myString As String * 10
    myString = "test"
    Debug.Print myString, "(" & Len(myString) & ")" '// Prints "test          (10)"

尽管这仅对右侧的填充有用。

于 2015-04-09T14:48:48.680 回答
1

我通过重新分配变量解决了这个问题。
在我的代码中,我从工作簿单元格获取数据并将其限制为 5 个字符(如有必要,填充足够的 0..):

MB = Right(String(5, "0") & Worksheets("HOME").Range("b3"), 5)
MB = Right(MB, 5)
于 2019-10-24T07:36:54.330 回答
1

合并前两个答案(感谢LittleBobbyTablesBrad)并注意辅助函数max,我建议:

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 最好命名为 minimumLength,因为始终返回整个原始字符串,可能导致结果比 minimumLength 长。

于 2020-08-13T13:12:20.453 回答
0

我对这个答案采取了不同的方法。它不是最简单的,但可能是最通用的。我使用了 LittleBobbyTables 和 Brad 的一些代码来制作这个。以下是有关如何使用该功能的几个示例:

Sub test()
    Debug.Print PadStr("ABC", 6) 'returns "ABC   "
    Debug.Print PadStr("ABC", 6, "-") 'returns "ABC---"
    Debug.Print PadStr("ABC", 6, , xlHAlignRight) 'returns "   ABC"
    Debug.Print PadStr("ABC", 7, "*", xlHAlignCenter) 'returns "**ABC**"
    Debug.Print PadStr("ABC", 9, "*", xlHAlignDistributed) 'returns "**A**B*C*"
    Debug.Print PadStr("ABC", 7, "*", xlHAlignFill) 'returns "ABCABCA"
End Sub

这是功能:

Function PadStr(Expression As Variant, length As Integer, Optional padChar As String = " ", Optional alignment As XlHAlign = xlHAlignGeneral) As String
'Pads a string with a given character.
'@Expression - the string to pad
'@length - the minimum length of the string (if @Expression is longer than @length, the original Expression will be returned)
'@padChar - the character to pad with (a space by default)
'@alignment - what type of alignment to use. Uses the XlAlign object for enumeration.
'   xlHAlignLeft            - (Default) Aligns input text to the left
'   xlHAlignGeneral         - Same as Default
'   xlHAlignRight           - Aligns input text to the right
'   xlHAlignCenter          - Center aligns text
'   xlHAlignCenterAcrossSelection       - Same as xlHAlignCenter
'   xlHAlignDistributed     - Distributes the text evenly within the length specified
'   xlHAlignJustify         - Same as xlHAlignDistributed
'   xlHAlignFill            - Fills the specified length with the text
'example: if input is "ABC", " ", "8", see code below for what the output will be given the different direction options
    If Len(Expression) >= length Or (padChar = "" And alignment <> xlHAlignFill) Then
        'if input is longer than pad-length padChar or no input given for padChar (note: padChar doesn't matter when
        'using xlHAlignFill) just return the input
        PadStr = Expression
    ElseIf Len(padChar) <> 1 And alignment <> xlHAlignFill Then
        'give error if padChar is not exactly 1 char in length (again, padChar doesn't matter when using xlHAlignFill)
        'padChar must be 1 char long because string() only accepts 1 char long input.
        Err.Raise vbObjectError + 513, , "input:'padChar' must have length 1." & vbNewLine & "SUB:PadStr"
    Else
        Dim pStr As String, i As Long
        Select Case alignment
            Case xlHAlignLeft, xlHAlignGeneral '(Default)
                '"ABC     "
                PadStr = CStr(Expression) & String(length - Len(CStr(Expression)), padChar)
            Case xlHAlignRight
                '"     ABC"
                PadStr = String(length - Len(CStr(Expression)), padChar) & CStr(Expression)
            Case xlHAlignCenter, xlHAlignCenterAcrossSelection
                '"   ABC  "
                pStr = String(Application.WorksheetFunction.RoundUp((length / 2) - (Len(Expression) / 2), 0), padChar)
                PadStr = pStr & Expression & pStr
            Case xlHAlignDistributed, xlHAlignJustify
                '"  A B C "       ("  A  B C " if lenth=9)
                Dim insPos As Long, loopCntr As Long: loopCntr = 1
                PadStr = Expression
                Do While Len(PadStr) < length
                    For i = 1 To Len(Expression)
                        PadStr = Left(PadStr, insPos) & padChar & Right(PadStr, Len(PadStr) - insPos)
                        insPos = insPos + 1 + loopCntr
                        If Len(PadStr) >= length Then Exit For
                    Next i
                    PadStr = PadStr & padChar
                    loopCntr = loopCntr + 1
                    insPos = 0
                Loop
            Case xlHAlignFill
                '"ABCABCAB"
                For i = 1 To Application.WorksheetFunction.RoundUp(length / Len(Expression), 0)
                    PadStr = PadStr & Expression
                Next i
            Case Else
                'error
                Err.Raise vbObjectError + 513, , "PadStr does not support the direction input ( " & direction & ")." & vbNewLine & "SUB:PadStr"
        End Select
        PadStr = Left(PadStr, length) 'output cannot be longer than the given length
    End If
End Function
于 2022-01-13T19:26:37.287 回答