Excel在公式栏中显示前导零

时间:2012-03-10 07:38:18

标签: excel excel-vba excel-formula vba

我有一个没有0的数据列表,所以我尝试了 Format Cells->Custom
添加一个前导零并且它可以工作。

但是当我点击每个单元格时,公式栏中显示的数据仍然没有前导零。例如,在自定义格式之后的excel文件中:
0112244555

但在公式栏中:
112244555

当我点击每个数据时,有没有办法显示带前导零的数据?

1 个答案:

答案 0 :(得分:7)

删除前导零是Excel中的默认行为。

使用自定义格式的解决方法是显示前导零的标准

如果你想实际嵌入它们,那么你需要添加一个撇号 即A1中 '012
将显示
012

作为文本 - 尽管您仍然可以对此单元格执行代数操作,就像它作为数字输入一样 12

代码解决方案

此代码将:

  • 仅在当前选择中运行数字常量单元格(即忽略空格,文本,公式)
  • 将在撇号
  • 后面添加两个前导零

因此,如果您在下面的A列上运行代码,结果将是C列中显示的更新单元格(仅用于演示,实际更新发生在A1,A4和A5中)

enter image description here

更改此行
strRep = "'00"
更改前导零的数量

  

'按Alt + F11打开Visual Basic编辑器(VBE)
  '来自   菜单,选择插入模块    '将代码粘贴到右侧代码中   窗口。
   '按Alt + F11关闭VBE
   '在Xl2003转到工具......   宏...宏并双击AddLeadingZeros

Sub AddLeadingZeros()
    Dim rng1 As Range
    Dim rngArea As Range
    Dim strRep As String
    Dim lngRow As Long
    Dim lngCol As Long
    Dim lngCalc As Long
    Dim X()

    strRep = "'00"

    On Error Resume Next
    'Set rng1 = Application.InputBox("Select range for the replacement of leading zeros", "User select", Selection.Address, , , , , 8)
    Set rng1 = Selection.SpecialCells(xlConstants, xlNumbers)
    If rng1 Is Nothing Then Exit Sub
    On Error GoTo 0

   'Speed up the code by turning off screenupdating and setting calculation to manual
   'Disable any code events that may occur when writing to cells
    With Application
        lngCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .EnableEvents = False
    End With

    'Test each area in the user selected range

    'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on
    For Each rngArea In rng1.Areas
        'The most common outcome is used for the True outcome to optimise code speed
        If rngArea.Cells.Count > 1 Then
           'If there is more than once cell then set the variant array to the dimensions of the range area
           'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks
            X = rngArea.Value2
            For lngRow = 1 To rngArea.Rows.Count
                For lngCol = 1 To rngArea.Columns.Count
                    'replace the leading zeroes
                    X(lngRow, lngCol) = strRep & X(lngRow, lngCol)
                Next lngCol
            Next lngRow
            'Dump the updated array sans leading zeroes back over the initial range
            rngArea.Value2 = X
        Else
            'caters for a single cell range area. No variant array required
            rngArea.Value = strRep & rngArea.Value2
        End If
    Next rngArea

    'cleanup the Application settings
    With Application
        .ScreenUpdating = True
        .Calculation = lngCalc
        .EnableEvents = True
    End With

End Sub