在前面添加零以满足字符串数 5 [重复]
Posted
技术标签:
【中文标题】在前面添加零以满足字符串数 5 [重复]【英文标题】:add zeros in front to meet string number of 5 [duplicate] 【发布时间】:2019-11-05 22:49:56 【问题描述】:我有 120、136、7120、72136 的值。最大字符串长度应该是 5,我该如何制作 120“00120”和 136“00136”等?
【问题讨论】:
单行将在 VBARange("A1").Value = "'" & Format(Range("A1").Value, "00000")
和 =TEXT(A1,"00000")
在 Excel 中工作
【参考方案1】:
单行即可
VBARange("A1").Value = "'" & Format(Range("A1").Value, "00000")
=TEXT(A1,"00000")
【讨论】:
【参考方案2】:在你的简单情况下,你可以尝试这样简单的事情:
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。
【讨论】:
【参考方案3】:Function FillWithZero(number as long, digitCount as long) as string
FillWithZero = Right(String(digitCount , "0") & number , digitCount)
End Function
【讨论】:
【参考方案4】:在您的单元格中使用自定义数字格式。 见Using a custom number format to display leading zeros 或Keeping leading zeros and large numbers
或.NumberFormat = "00000"
在您的范围内。
我不建议将其转换为字符串(除非它是不被视为实际数字的序列号)。
【讨论】:
【参考方案5】:与 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
【讨论】:
请注意,这是您可以拥有的最慢的想法,并且会将数字转换为(mabye)无用的字符串(不再进行计算)。此外,您可能想查看String(ExpectedLength - Len(str), "0")
以摆脱循环。
@Pᴇʜ 记录和编辑!以上是关于在前面添加零以满足字符串数 5 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
TextInput 从右到左输入数字并自动添加零以进行货币输入