Vba:显示带点的小数而不是昏迷

我想在一个macros中显示所有的数字,而不是昏迷

对于实例这个显示“0,03”,但我想“0.03”:

Dim MyNumber As Single MyNumber = 0.03 MsgBox (MyNumber) 

我尝试了一套不起作用的代码:

  • 这仍然显示昏迷:

     Application.DecimalSeparator = "." 
  • 这仍然显示昏迷,并不适用于整个macros

     MyNumber = Format(MyNumber, "##0.00") 
  • 这显示点而不是昏迷,但不适用于整个macros

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

谢谢!

说起来容易做起来难。 在VBA编辑器中,小数点分隔符是点。 但是,MsgBox函数(和格式函数)将使用Windows区域设置,而不是Excel设置来格式化其结果。

为了使MsgBox使用您select的格式设置显示一个数字,您需要创build一个string,其值可以根据需要进行格式化。

这是一个这样做的方法:


 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 

请注意,如果要同时使用小数点和千位分隔符,并且如果要交换逗号和点,则需要这样做两次,以免用点replace所有逗号,反之亦然


 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 

很有可能您的Excel设置导致冲突。

 1. On the File tab, click the Options button 2. Click the Advanced tab 3. Clear/Uncheck the "Use system separators" option. 

然后尝试你的代码。

作为第一步,Kernel32dynamic链接库的三个函数波纹pipe必须声明:

 Private Declare Function GetUserDefaultLCID% Lib "kernel32" () Private Declare Function GetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long Private Declare Function SetLocaleInfoA Lib "kernel32" ( ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As Boolean 
  • 第一个将获得用户的默认ID
  • 第二个将有助于获得当地人的价值(因此恢复)
  • 第三个将有助于确定当地人的价值

小数的本地types值是14(有些喜欢写&HE – hexE – )

然后程序看起来像这样:

 ' record the settings in the variable LocalSettingsDecimal Dim LocalSettingsDecimal As String Dim Buffer As String Buffer = String(256, 0) Dim le As Integer le = GetLocaleInfoA(GetUserDefaultLCID(), 14, Buffer, Len(Buffer)) LocalSettingsDecimal = Left(Buffer, le - 1) ' force decimal settings to '.' Call SetLocaleInfoA(GetUserDefaultLCID(), 14, ".") ' body Dim MyNumber As Single MyNumber = 0.03 MsgBox (MyNumber) ' set back the decimal settings Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal) 

让我们注意到,不幸的是,在程序主体失败的情况下,设置不会恢复…但这仍然可以解决问题