Excel在公式栏中显示前导零

Ire*_*ing 0 excel vba excel-vba excel-formula

我有一个没有0的数据列表,所以我试图
Format Cells->Custom
添加一个前导零,它的工作原理.

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

但在公式栏中:
112244555

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

bre*_*tdj 7

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

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

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

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

代码解决方案

此代码将:

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

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

在此输入图像描述

更改此行
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
Run Code Online (Sandbox Code Playgroud)