【发布时间】:2019-11-05 22:49:56
【问题描述】:
我有 120、136、7120、72136 的值。最大字符串长度应该是 5,我该如何制作 120“00120”和 136“00136”等?
【问题讨论】:
-
单行将在 VBA
Range("A1").Value = "'" & Format(Range("A1").Value, "00000")和=TEXT(A1,"00000")在 Excel 中工作
我有 120、136、7120、72136 的值。最大字符串长度应该是 5,我该如何制作 120“00120”和 136“00136”等?
【问题讨论】:
Range("A1").Value = "'" & Format(Range("A1").Value, "00000") 和 =TEXT(A1,"00000") 在 Excel 中工作
单行即可
Range("A1").Value = "'" & Format(Range("A1").Value, "00000")
=TEXT(A1,"00000")
【讨论】:
在你的简单情况下,你可以尝试这样简单的事情:
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。
【讨论】:
Function FillWithZero(number as long, digitCount as long) as string
FillWithZero = Right(String(digitCount , "0") & number , digitCount)
End Function
【讨论】:
在您的单元格中使用自定义数字格式。
见Using a custom number format to display leading zeros
或Keeping leading zeros and large numbers
或.NumberFormat = "00000" 在您的范围内。
我不建议将其转换为字符串(除非它是不被视为实际数字的序列号)。
【讨论】:
与 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
【讨论】:
String(ExpectedLength - Len(str), "0") 以摆脱循环。