【问题标题】:add zeros in front to meet string number of 5 [duplicate]在前面添加零以满足字符串数 5 [重复]
【发布时间】: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 中工作

标签: excel vba


【解决方案1】:

单行即可

  • VBA

Range("A1").Value = "'" & Format(Range("A1").Value, "00000")

  • Excel

=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ᴇʜ 记录和编辑!
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-12
          • 2016-06-19
          • 1970-01-01
          • 2017-07-29
          • 1970-01-01
          • 2023-03-26
          • 2021-07-26
          相关资源
          最近更新 更多