VBAを使用したUltimate1000セパレーター

Aug 16 2020

私の場合、数式を使用することはできず、カスタムコードを使用する必要があるため、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

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

回答

5 SuperSymmetry Aug 16 2020 at 19:40

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

別のアプローチは、レジストリからセパレータを読み取ることです。これは、さまざまな地域の設定で機能するはずです。

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

Application.International@RonRosenfeldによって提案されたように使用するように変更された関数を編集します。

1 TinMan Aug 16 2020 at 23:38

より大きな数を含めるには、数の形式を拡張する必要があります。

### ### ## 0 "、"