【发布时间】:2015-01-12 15:29:11
【问题描述】:
我正在寻找将双精度数转换为字符串的解决方案,但字符串的小数位前应该有逗号,而不是点。
“一个半”应该是 1,5(德语符号)。
感谢您的帮助!!
【问题讨论】:
我正在寻找将双精度数转换为字符串的解决方案,但字符串的小数位前应该有逗号,而不是点。
“一个半”应该是 1,5(德语符号)。
感谢您的帮助!!
【问题讨论】:
CStr 和 Replace 的组合可以完成这项工作。
Function Dbl2Str(dbl As Double) As String
Dbl2Str = Replace(CStr(dbl), ".", ",")
End Function
【讨论】:
不幸的是,在 VBA 中,您无法轻松编写与语言环境无关的代码。也就是说,当您进行 CStr 演员表时,您不能指定语言环境。
一种解决方法是将 0.5 之类的双精度数转换为字符串,然后查看最终结果。如果您以 0,5 结尾,那么您处于德语(等)语言环境中,您无需执行任何其他操作。
如果您最终得到0.5,那么您知道您需要进行转换。然后你只需要遍历你的字符串,用逗号替换点,反之亦然(反之亦然,以防你的字符串有数千个分隔符)。你可以使用Replace。
【讨论】:
根据 RubberDuck 的评论,我得到了这样的结果:
Function DblToStr(x As Double)
DblToStr = CStr(x)
If (Application.ThousandsSeparator = ".") Then
DblToStr = Replace(DblToStr, ".", "")
End If
If (Application.DecimalSeparator = ".") Then
DblToStr = Replace(DblToStr, ".", ",")
End If
End Function
【讨论】:
然后是这样的
Dim somestring As String
Dim someDec As Double
someDec = 1.5
somestring = CStr(someDec)
somestring = Replace(somestring, ".", ",")
MsgBox (somestring)
【讨论】:
选择您要转换的单元格并运行这个小宏:
Sub changeIT()
For Each r In Selection
t = r.Text
If InStr(1, r, ".") > 0 Then
r.Clear
r.NumberFormat = "@"
r.Value = Replace(t, ".", ",")
End If
Next r
End Sub
只有那些带有 "." 的单元格会改变,它们将是 Strings 而不是 Doubles
【讨论】:
我检查了其他答案,但最终编写了自己的解决方案,使用以下代码将1500.5 等用户输入转换为1,500.50:
'
' Separates real-numbers by "," and adds "." before decimals
'
Function FormatNumber(ByVal v As Double) As String
Dim s$, pos&
Dim r$, i&
' Find decimal point
s = CStr(v)
pos = InStrRev(s, ".")
If pos <= 0 Then
pos = InStrRev(s, ",")
If pos > 0 Then
Mid$(s, pos, 1) = "."
Else
pos = Len(s) + 1
End If
End If
' Separate numbers into "r"
On Error Resume Next
i = pos - 3
r = Mid$(s, i, 3)
For i = i - 3 To 1 Step -3
r = Mid$(s, i, 3) & "," & r
Next i
If i < 1 Then
r = Mid$(s, 1, 2 + i) & "," & r
End If
' Store dot and decimal numbers into "s"
s = Mid$(s, pos)
i = Len(s)
If i = 2 Then
s = s & "0"
ElseIf i <= 0 Then
s = ".00"
End If
' Append decimals and return
FormatNumber = r & s
End Function
【讨论】: