我在excel中有一个H列,其值为以下类型
158.60
158.60
170.58
数字格式为现在我需要将其更改为类似以下
158,60
158,60
170,58
我完成了以下代码,但结果却显得很奇怪......
Dim ws1 As Worksheet
Dim lastRowk As Long
Set ws1 = ThisWorkbook.Sheets("Sheet1")
lastRowk = ws1.Cells(Rows.Count, "H").End(xlUp).Row
For Each m In ws1.Range("H2:H" & lastRowk)
m.Value = "'" & m.Value
Next m
Worksheets("Sheet1").Columns("H").Replace What:=".", Replacement:=",", SearchOrder:=xlByColumns, MatchCase:=True
For Each m In ws1.Range("H2:H" & lastRowk)
If m.Value Like "*,*" Then
'Nothing
Else
m.Value = m.Value & ",00"
End If
Next m
我得到的结果如下:
158,59742
158,59742
170,57936
但我希望它像下面的
158,59
158,59
170,57
答案 0 :(得分:0)
看到你的最终结果,它根本不奇怪。它看起来像你的初始值确实是数字,但形成为### 9.99所以它们只显示逗号后的2位数字。然而,这只是显示,Excel保留您的数字的实际值,显然有5位数。
一个简单的解决方案是在制作你的东西之前将小数部分舍入到只有2位数:
cell.value = round(cell.value,2)
另一个解决方案,保留您已经完成的工作,将在操作结束时舍入最后两位数字:
For Each m In ws1.Range("H2:H" & lastRowk)
If m.Value Like "*,*" Then
Dim i As Integer
Dim strBefore As String
Dim strAfter As String
Dim dblTemp As Double
Dim strTemp As String
dim strDecimalSign as string
' Change this according to the decimal sign on your system:
strDecimalSign = ","
' or :
' strDecimalSign = "."
' get comma position
i = InStr(m.value, ",")
' get the value before the comma
strBefore = Left(m.value, i - 1)
' get the value after the comma
strAfter = Mid(m.value, i + 1)
' make a temp double with 2 digits
dblTemp = Round(CDbl("0" & strDecimalSign & strAfter), 2)
' Convert back to string
strTemp = CStr(dblTemp)
' keep only the rounded 2 digits part
strAfter = Replace(strTemp, "0" & strDecimalSign, "")
'join all parts
m.value = strBefore & "," & strAfter
Else
m.Value = m.Value & ",00"
End If
Next m
(写在我的手机上,所以未经测试。)
您可能会研究的第三种解决方案是更改decimalseparator格式: http://msdn.microsoft.com/en-us/library/office/ff195207(v=office.15).aspx