How to make Excel doesn't truncate 0's in formatting decimal numbers?

折月煮酒 提交于 2019-12-08 01:57:31

问题


Suppose that I have the following random numbers in Notepad:

1.19
0.040
10.1123
23.110
21.223
2.35456
4.0
10234.0009
456798.7500
123
34.560
40060
33.7876

If I copy the numbers above and paste them in Excel, the number formats will change to this

1.19
0.04
10.1123
23.11
21.223
2.35456
4
10234.0009
456798.75
123
34.56
40060
33.7876

I intend to copy-paste the numbers without changing their original formats, for examples:

  • 0.040 keeps 0.040, not 0.04;

  • 4.0 keeps 4.0, not 4;

  • 456798.7500 keeps 456798.7500, not 456798.75; and so on.

I'm aware that I can use conditional formattings like

If condition_1 Then
   Cells(...).NumberFormat = "0.00"

ElseIf condition_2 Then
   Cells(...).NumberFormat = "0.000"

...

Else
   result_else

End If

or use Select ... Case Statement, but the problems with these methods are:

  1. The code can be lengthy and looks messy.
  2. If the numbers change, then the conditionals must change, too.

So my question is:

How to make Excel doesn't truncate the 0's in the end of decimal numbers?

P.S. I want to keep the values as numbers, not texts.


Addendum: I don't understand why does one downvote this OP since this kind of representation does matter in financial data for example: foreign exchange or currency rate.


回答1:


If I place your original data in column A (with your posted formats) and run this:

Sub CopyFull()
    Dim A As Range, B As Range

    Set A = Range("A1:A13")
    Set B = Range("B1:B13")
    A.Copy B
End Sub

The copied data items will have the same formats as the originals:

So if A9 has a NumberFormat of 0.0000, then so will B9.

EDIT#1:

If the data started out in an open NotePad process, I would:

  1. manually (or programmatically) store the data as a text file (.txt)
  2. import the text file into a column as Text
  3. convert each item in the column into a Number with a NumberFormat consistent with the text format



回答2:


If there was any accompanying column with an identifier that could be used to group the numerical values into currency format categories then the problem becomes simple¹.


                        Data before running the currencyConditionals sub procedure

                  • EUR should use €, have 3 decimal places and be green
                  • JPN should use ¥, have 4 decimal places and be dark red
                  • GPD should use £, have 0 decimal places and be dark blue
                  • USD should use $, have 2 decimal places and be blue

Run the code.

Option Explicit

Sub currencyConditionals()
    Dim a As Long, aCURRs As Variant, aFRMTS As Variant

    aCURRs = Array("EUR", "JPY", "GBP", "USD")
    aFRMTS = Array("[color10]_([$€-2]* #,##0.000_);[color3]_([$€-2]* (#,##0.000);[color15]_(* -??_);[color46]_(@_)", _
                   "[color9]_([$¥-411]* #,##0.0000_);[color9]_=[$¥-411]* (#,##0.0000);[color15]_(* -??_);[color46]_(@_)", _
                   "[color11]_([$£-809]* #,##0_-;[color11]-[$£-809]* #,##0_-;[color15]_-[$£-809]* -_);[color46]_-@_-", _
                   "[color5]_($* #,##0.00_);[color5]_($* (#,##0.00);[color15]_($* -??_);[color46]_(@_)")

    With Worksheets("Sheet2")
        With .Cells(1, 1).CurrentRegion
            With .Offset(1, 5).Resize(.Rows.Count - 1, 1)
                .FormatConditions.Delete
                For a = LBound(aCURRs) To UBound(aCURRs)
                    With .FormatConditions.Add(Type:=xlExpression, _
                                Formula1:="=$C2=" & Chr(34) & aCURRs(a) & Chr(34))
                        .NumberFormat = aFRMTS(a)
                    End With
                Next a
            End With
        End With
    End With
End Sub


                        Data after running the currencyConditionals sub procedure


¹ Examples of formatting mask codes can be found at Number Format Code.




回答3:


Though this code is a bit messy, but at least I try what Gary's Student suggests in his answer (See EDIT#1). Suppose that I want to place the original data in column A and the desired formats in column B, then I will:

  1. Set Number Format in Column A as Text. To do this, click column A heading and look for the Number section of the Home menu tab then click the arrow in the lower right corner of the Number section and choose Text.
  2. Copy (CtrlC) the original data in Notepad then click cell A1 and paste (CtrlV) the data.

Run this code:

Sub Keeping_Number_Format_1()
Last_Row = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To Last_Row
   'Determine the number of the decimal places
   Dec_Number = Len(Cells(i, 1)) - InStr(Cells(i, 1), ".")

   'Return the number found in the input string (each cells in column A)
   Cells(i, 2) = Val(Cells(i, 1))

   'Set the data in column B to specific formats
   If Dec_Number = Len(Cells(i, 1)) Then
      Cells(i, 2).NumberFormat = "0"
   ElseIf Dec_Number = 1 Then
      Cells(i, 2).NumberFormat = "0.0"
   ElseIf Dec_Number = 2 Then
      Cells(i, 2).NumberFormat = "0.00"
   ElseIf Dec_Number = 3 Then
      Cells(i, 2).NumberFormat = "0.000"
   ElseIf Dec_Number = 4 Then
      Cells(i, 2).NumberFormat = "0.0000"
   'I add these lines just in case the given numbers exceed 4 decimal places.
   'You can add the lines as you wish.
   ElseIf Dec_Number = 5 Then
      Cells(i, 2).NumberFormat = "0.00000"
   ElseIf Dec_Number = 6 Then
      Cells(i, 2).NumberFormat = "0.000000"
   End If
Next i
End Sub

or one may run the shorter version of the above code. It employs the REPT function in Microsoft Excel so that one doesn't need to change the code in the future since it works for data with any number of decimal places.

Sub Keeping_Number_Format_2()
Last_Row = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To Last_Row
   Dec_Number = Len(Cells(i, 1)) - InStr(Cells(i, 1), ".")
   Cells(i, 2) = Val(Cells(i, 1))

   If Dec_Number = Len(Cells(i, 1)) Then
      Cells(i, 2).NumberFormat = "0"
   Else
      Cells(i, 2).NumberFormat = "0." & WorksheetFunction.Rept("0", Dec_Number)
   End If

Next i
End Sub


来源:https://stackoverflow.com/questions/38305551/how-to-make-excel-doesnt-truncate-0s-in-formatting-decimal-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!