我的值是120、136、7120、72136。最大字符串长度应为5,如何制作120“ 00120”和136“ 00136”等?
答案 0 :(得分:3)
单行即可工作
Range("A1").Value = "'" & Format(Range("A1").Value, "00000")
=TEXT(A1,"00000")
答案 1 :(得分:1)
在简单的情况下,您可以尝试类似以下的简单操作:
Sub FiveCharString()
Dim myStr As String
myStr = "136"
If Len(myStr) = 2 Then
myStr = "000" & myStr
ElseIf Len(myStr) = 3 Then
myStr = "00" & myStr
ElseIf Len(myStr) = 4 Then
myStr = "0" & myStr
End If
Debug.Print myStr
End Sub
返回00136。
答案 2 :(得分:1)
Function FillWithZero(number as long, digitCount as long) as string
FillWithZero = Right(String(digitCount , "0") & number , digitCount)
End Function
答案 3 :(得分:1)
在单元格中使用自定义数字格式。
参见Using a custom number format to display leading zeros
或Keeping leading zeros and large numbers
或您范围内的.NumberFormat = "00000"
。
我不建议将其转换为字符串(除非它是类似序列号的东西,而不是实际数字)。
答案 4 :(得分:1)
比Dean的版本更简单的版本
Sub StrLength()
Dim i As Long, str As String
str = "136"
i = Len(str)
StrLength = String(ExpectedLength - Len(str), "0") & str
End Sub
小的子例程很容易用作Functions,您可以在常规子例程中调用该函数。例如,当您遍历一系列单元格时:
Function StrLength(str As String, ExpectedLength As Long) As String
Dim i As Long
i = Len(str)
StrLength = String(ExpectedLength - Len(str), "0") & str
End Function
Sub Test()
Dim c As Range
For each c In ThisWorkbook.Sheets(1).Range("A1:B200")
If Len(c.Value) < 5 Then c.Value = StrLength(Str:=c.Value, ExpectedLength:=5)
Next c
End Sub