只是想知道,VBA 中是否有与 VB .NET 的 PadLeft 和 PadRight 方法等效的方法?
截至目前,每当我想要获取一个字符串并使其具有前导空格的固定长度时,我都会根据字符串的长度执行 For...Next 循环。
例如,我将使用以下代码将字符串格式化为 8 个字符并带有前导空格:
intOrdNoLen = Len(strOrdNo)
For i = 1 To (8 - intOrdNoLen) Step 1
strOrdNo = " " & strOrdNo
Next
有没有办法在 VBA 中以更少的行数完成同样的事情?
我不相信有任何明确的
PADLEFT
或 PADRIGHT
函数,但您可以使用 SPACE
和 LEFT
或 RIGHT
的组合在字符串前面添加空格,然后抓住正确的 X字符数。
左键
strOrdNo = RIGHT(Space(8) & strOrdNo, 8)
如果您想要一个字符而不是空格,可以使用
STRING
代替空格(下面的示例用 X 填充左侧):
strOrdNo = RIGHT(String(8, "X") & strOrdNo, 8)
PADRIGHT
strOrdNo = LEFT(strOrdNo & Space(8), 8)
strOrdNo = LEFT(strOrdNo & String(8, "X"), 8)
你可以使用这些。将它们放在公共模块中
'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
由于我们通常在左侧填充,因此 Format() 函数更短、更简单:
Format(number, " ")
Format(number, "00")
Format("abc","!@@@@@@") ' width >= 6; pad right side with spaces
Format("abc","@@@@@@") ' width >= 6; pad left side with spaces
您还可以在 VBA 中使用固定长度字符串:
Dim myString As String * 10
myString = "test"
Debug.Print myString, "(" & Len(myString) & ")" '// Prints "test (10)"
虽然这仅对右侧填充有用。
我通过重新分配变量解决了这个问题。
在我的代码中,我从工作簿单元格获取数据并将其限制为 5 个字符(如果需要,请填充足够的 0..):
MB = Right(String(5, "0") & Worksheets("HOME").Range("b3"), 5)
MB = Right(MB, 5)
合并前两个答案(感谢LittleBobbyTables和Brad)并注意辅助函数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 长。
我对这个答案采取了不同的方法。它不是最简单的,但可能是最通用的。我使用了 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
您可以使用下面的函数来填充字符串而不是单个字符:
Function PadLeft(ByVal inputString, ByVal totalWidth, ByVal padding)
IF Len(padding) < 1 Then padding = " "
Do While Len(inputString) < totalWidth
inputString = padding & inputString
Loop
PadLeft = RIGHT(inputString, totalWidth)
End Function
Function PadRight(ByVal inputString, ByVal totalWidth, ByVal padding)
IF Len(padding) < 1 Then padding = " "
Do While Len(inputString) < totalWidth
inputString = inputString & padding
Loop
PadRight = Left(inputString, totalWidth)
End Function