Удаление начальных нулей - это стандартное поведение в Excel.
Ваш обходной путь для использования нестандартного формата является стандартным для отображения начальных нулей
Если вы действительно хотите встроить их, вам потребуетсядобавив апостроф, т.е. в A1
'012
отобразит
012
в виде текста - хотя вы все равно можете выполнять алгебраические манипуляции с этой ячейкой, как если бы она была введена как числовой
12
Кодовое решение
Этот код будет:
- работать только с числовыми константами в текущем выборе (т. Е.игнорируя пробелы, текст, формулы)
- добавит два ведущих нуля за апострофом
Так что если вы запустите код в столбце A ниже, результатом будут обновленные ячейки, показанные встолбец C (только для демонстрации, фактические обновления происходят в A1, A4 и A5)
![enter image description here](https://i.stack.imgur.com/bjeSG.png)
Измените эту строку
strRep = "'00"
, чтобы изменить суммуведущие нули
'Нажмите Alt + F11, чтобы открытьРедактор Visual Basic (VBE)
'В меню выберите Вставить-модуль.
' Вставьте код в правое окно кода.
'Нажмите Alt + F11, чтобы закрыть VBE
«В Xl2003 Goto Tools… Макрос… Макросы и двойной щелчок 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