问题
I have been trying to get VBA solution for 1000 separator as in my case it is not possible to use formula and should be done with custom code. Current solution is taken from answer Number Format with Thousands Separator and Decimal if Necessary
Here is the code:
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
It is working for numbers like 1000, but it does not work for 1000000. Also 1000000000 will not work. I am currently working on solution, but if somebody has something to share, it would be appreciated.
In case of using original solution:
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
回答1:
I think vba needs the thousands separater that is defined in your regional settings. Since it is a comma in your case you can do something like this
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
Another approach is to read the separator from the registry. This should work in different regional settings.
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
Edit Changed function to use Application.International as suggested by @RonRosenfeld.
回答2:
You need to extend your number format to include the larger numbers.
### ### ##0","

来源:https://stackoverflow.com/questions/63436786/ultimate-1000-separator-using-vba