Pemisah 1000 Ultimate menggunakan VBA

Aug 16 2020

Saya telah mencoba mendapatkan solusi VBA untuk 1000 pemisah karena dalam kasus saya, tidak mungkin menggunakan rumus dan harus dilakukan dengan kode khusus. Solusi saat ini diambil dari format angka jawaban dengan ribuan pemisah dan desimal jika diperlukan

Ini kodenya:

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

Ini bekerja untuk angka seperti 1000, tetapi tidak bekerja untuk 1000000. Juga 1000000000 tidak akan bekerja. Saat ini saya sedang mengerjakan solusi, tetapi jika seseorang memiliki sesuatu untuk dibagikan, itu akan sangat dihargai.

Jika menggunakan solusi asli:

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

Jawaban

5 SuperSymmetry Aug 16 2020 at 19:40

Saya pikir vba membutuhkan ribuan pemisah yang ditentukan dalam pengaturan regional Anda. Karena ini adalah koma dalam kasus Anda, Anda dapat melakukan sesuatu seperti ini

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

Pendekatan lain adalah membaca pemisah dari registri. Ini harus bekerja di pengaturan regional yang berbeda.

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 fungsi Berubah untuk digunakan Application.Internationalseperti yang disarankan oleh @RonRosenfeld.

1 TinMan Aug 16 2020 at 23:38

Anda perlu memperluas format angka Anda untuk memasukkan angka yang lebih besar.

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