我想以这种方式格式化单元格值:
1234,980 - > 1.234,980
12237119867,761 - > 12.237.119.867,761
如何准备一个公共掩码,将点设置为千位分隔符,将逗号设置为小数。掩码应该适用于任何提供的值。
答案 0 :(得分:5)
定义小数点左侧的第一个段。它会根据需要自动复制 点后面的octothorpes数设置点后的最大小数位数,只需要使用的所需数量。
类似的东西:
#.###,0##
(我假设这对你当前的语言环境有效。)
根据phoog的评论建议,与语言环境无关的格式为:
#,###.0##
(用于使用Cell.NumberFormat = "#,###.0##"
设置格式)
对于某些VBA代码,您可能拥有Format
函数的增强版本,该函数接受两个区域设置,一个是格式字符串,另一个用于格式化结果。
将以下内容放在一个单独的模块中:
Option Explicit
Private Declare Function VarTokenizeFormatString Lib "oleaut32.dll" (ByVal pstrFormat As Long, ByRef rgbTok As Any, ByVal cbTok As Long, ByVal iFirstDay As VbDayOfWeek, ByVal iFirstWeek As VbFirstWeekOfYear, ByVal lcid As Long, ByRef pcbActual As Long) As Long
Private Declare Function VarFormatFromTokens Lib "oleaut32.dll" (ByRef pvarIn As Variant, ByVal pstrFormat As Long, ByRef pbTokCur As Any, ByVal dwFlags As Long, ByRef pbstrOut As Long, ByVal lcid As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Const S_OK As Long = 0
Private Const E_INVALIDARG As Long = &H80070057
Private Const E_OUTOFMEMORY As Long = &H8007000E
Private Const DISP_E_BUFFERTOOSMALL As Long = &H80020013
Private Const DISP_E_TYPEMISMATCH As Long = &H80020005
Public Function FormatForLocale(ByVal Expression As Variant, Optional ByVal Format As String, Optional ByVal FirstDayOfWeek As VbDayOfWeek = vbUseSystemDayOfWeek, Optional ByVal FirstWeekOfYear As VbFirstWeekOfYear = vbUseSystem, Optional ByVal PatternLocaleID As Long = 0, Optional ByVal TargetLocaleID As Long = 0) As String
Dim b() As Byte, t As Long
Dim hResult As Long
Dim pBstrResult As Long, res As String
Const CHUNK_SIZE As Long = 256
If TypeOf Expression Is Excel.Range Then
Expression = Expression.Value
End If
ReDim b(1 To CHUNK_SIZE)
Do
hResult = VarTokenizeFormatString(StrPtr(Format), b(LBound(b)), UBound(b) - LBound(b) + 1, FirstDayOfWeek, FirstWeekOfYear, PatternLocaleID, t)
Select Case hResult
Case S_OK
Exit Do
Case E_INVALIDARG
Err.Raise 5, , "Some arguments are invalid."
Case DISP_E_BUFFERTOOSMALL
ReDim b(LBound(b) To UBound(b) + CHUNK_SIZE)
Case Else
Err.Raise 5, , "Internal error. Unexpected error code returned from system."
End Select
Loop
Select Case VarFormatFromTokens(Expression, StrPtr(Format), b(LBound(b)), 0, pBstrResult, TargetLocaleID)
Case S_OK
CopyMemory ByVal VarPtr(res), pBstrResult, 4
Case E_OUTOFMEMORY
Err.Raise 7
Case E_INVALIDARG
Err.Raise 5, , "Some arguments are invalid."
Case DISP_E_TYPEMISMATCH
Err.Raise 5, , "The argument could not be coerced to the specified type."
Case Else
Err.Raise 5, , "Internal error. Unexpected error code returned from system."
End Select
FormatForLocale = res
End Function
现在您有一个函数FormatForLocale
,它模仿默认的VBA Format
函数,但添加了两个额外的参数。要获得所需的结果,您可以:
result = FormatForLocale(123456789, "#,###.0##", , , LOCALE_INVARIANT, LOCALE_GERMAN)
其中LOCALE_INVARIANT
和LOCALE_GERMAN
是常量,您可以查看here。
您也可以从工作表中调用它:
=FormatForLocale(123456789,"#,###.0##",,,127,3079)