使用 VBA 的 Ultimate 1000 分隔符

hat*_*man 1 excel vba

我一直在尝试获得 1000 分隔符的 VBA 解决方案,因为在我的情况下,不可能使用公式,应该使用自定义代码来完成。当前解决方案取自答案数字格式,如果需要,带有千位分隔符和十进制

这是代码:

Function CustomFormat(InputValue As Double) As String
    CustomFormat = Format(InputValue, "# ###")
    If (Right(CustomFormat, 1) = ".") Then
        CustomFormat = Left(CustomFormat, Len(CustomFormat) - 1)
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

它适用于 1000 之类的数字,但不适用于 1000000。另外 1000000000 也不起作用。我目前正在研究解决方案,但如果有人要分享一些东西,我们将不胜感激。

如果使用原始解决方案:

Function CustomFormat(InputValue As Double) As String
    CustomFormat = Format(InputValue, "#,###.##")
    If (Right(CustomFormat, 1) = ".") Then
        CustomFormat = Left(CustomFormat, Len(CustomFormat) - 1)
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Sup*_*try 5

我认为 vba 需要在您的区域设置中定义的数千个分隔符。由于在您的情况下它是逗号,因此您可以执行以下操作

Function CustomFormat(InputValue As Double) As String
    CustomFormat = Format(InputValue, "#,###")
    If (Right(CustomFormat, 1) = ".") Then
        CustomFormat = Left(CustomFormat, Len(CustomFormat) - 1)
    End If
    CustomFormat = Replace(CustomFormat, ",", " ")
End Function
Run Code Online (Sandbox Code Playgroud)

另一种方法是从注册表中读取分隔符。这应该适用于不同的区域设置。

Function CustomFormat(InputValue As Double) As String
    Dim sThousandsSep As String
    Dim sDecimalSep As String
    Dim sFormat As String
    
    sThousandsSep = Application.International(xlThousandsSeparator)
    sDecimalSep = Application.International(xlDecimalSeparator)
    
    ' Up to 6 decimal places
    sFormat = "#" & sThousandsSep & "###" & sDecimalSep & "######"
    
    CustomFormat = Format(InputValue, sFormat)
    If (Right$(CustomFormat, 1) = sDecimalSep) Then
        CustomFormat = Left$(CustomFormat, Len(CustomFormat) - 1)
    End If
    
    ' Replace the thousands separator with a space
    ' or any other character
    CustomFormat = Replace(CustomFormat, sThousandsSep, " ")
End Function
Run Code Online (Sandbox Code Playgroud)

Application.International按照@RonRosenfeld 的建议,编辑更改的函数以使用。

  • 供参考。您还可以使用“Application.International(xlThousandsSeparator)”和“Application.International(xlDecimalSeparator)”获取 VBA 中千位和小数分隔符的设置 (2认同)