ตัวคั่นสุดยอด 1,000 โดยใช้ VBA

Aug 16 2020

ฉันพยายามรับโซลูชัน VBA สำหรับตัวคั่น 1,000 ในกรณีของฉันมันเป็นไปไม่ได้ที่จะใช้สูตรและควรใช้โค้ดที่กำหนดเอง โซลูชันปัจจุบันนำมาจากคำตอบรูปแบบตัวเลขที่มีตัวคั่นหลักพันและทศนิยมหากจำเป็น

นี่คือรหัส:

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,000 แต่ใช้ไม่ได้กับ 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 ","