Separador Ultimate 1000 usando VBA

Aug 16 2020

He estado tratando de obtener una solución VBA para el separador 1000, ya que en mi caso no es posible usar la fórmula y debería hacerse con un código personalizado. La solución actual se toma del formato de número de respuesta con separador de miles y decimal si es necesario

Aquí está el código:

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

Funciona para números como 1000, pero no funciona para 1000000. Además, 1000000000 no funcionará. Actualmente estoy trabajando en una solución, pero si alguien tiene algo que compartir, se lo agradecería.

En caso de utilizar solución original:

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

Respuestas

5 SuperSymmetry Aug 16 2020 at 19:40

Creo que vba necesita el separador de miles que se define en su configuración regional. Como es una coma en su caso, puede hacer algo como esto

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

Otro enfoque es leer el separador del registro. Esto debería funcionar en diferentes entornos regionales.

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

Editar función modificada para usar Application.Internationalcomo lo sugiere @RonRosenfeld.

1 TinMan Aug 16 2020 at 23:38

Debe ampliar el formato de su número para incluir los números más grandes.

### ### ## 0 ","