Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

excel - Vba: display decimals with point and not coma

I would like to have all numbers in a macro displayed with point and not coma

For Instance This display "0,03" but I would like "0.03":

Dim MyNumber As Single
MyNumber = 0.03
MsgBox (MyNumber)

I have tried a set of codes that does not work:

  • this still displays the Coma:

    Application.DecimalSeparator = "."
    
  • this still displays the Coma and does not apply to the whole macro

    MyNumber = Format(MyNumber, "##0.00")
    
  • this displays dot instead of coma but does not apply to the whole macro

    MsgBox (Replace(MyNumber, ",", "."))
    

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is easier said than done. In the VBA editor, the decimal separator is the dot. However, the MsgBox function (and the Format function) will use the windows regional settings, and not the Excel settings, to format its results.

In order to have the MsgBox display a number using format settings of your choice, you need to create a string that has the value formatted as you want.

Here is one way of doing that:


Option Explicit
Sub dural()
 Dim S As String
 Dim D As Double
 Const myDecSep As String = "."

D = 1234.56

S = Format(D, "0.00") 'will format using the system separator

S = Replace(S, Application.DecimalSeparator, myDecSep)

MsgBox S

End Sub

Note that if you want to use both decimal and thousands separators, and if you are interchanging, for example, the comma and the dot, you need to do this twice so as not to replace all your commas with dots, or vice-versa


Option Explicit
Sub dural()
 Dim S As String
 Dim D As Double
 Const myDecSep As String = "."
 Const myThousSep As String = ","

D = 1234.56

S = Format(D, "#,##0.00")

S = Replace(S, Application.DecimalSeparator, Chr(1))
S = Replace(S, Application.ThousandsSeparator, Chr(2))
S = Replace(S, Chr(1), myDecSep)
S = Replace(S, Chr(2), myThousSep)

MsgBox S

End Sub


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...