วันจันทร์ที่ 9 กรกฎาคม พ.ศ. 2561

VBA : แปลงตัวเลขเป็นตัวอักษร

       มี Function BathText() สำหรับแปลงตัวเลขเป็นตัวอักษร มาฝาก ซึ่งสามารถ copy และนำไปใช้ได้ เลย ครับ
Code

Public Function BahtText(ByVal sNum)
Dim sNumber, sDigit, sDigit10
Dim nLen, sWord, sWord2
Dim sByte, i, J

sNumber = Array("", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า")
sDigit = Array("", "สิบ", "ร้อย", "พัน", "หมื่น", "แสน")
sDigit10 = Array("", "สิบ", "ยี่สิบ", "สามสิบ", "สี่สิบ", "ห้าสิบ", "หกสิบ", "เจ็ดสิบ", "แปดสิบ", "เก้าสิบ")
sNum = Replace(FormatNumber(sNum, 2), ",", "")
nLen = Len(sNum)

If sNum = ".00" Then BahtText = "ศูนย์"
For i = 1 To nLen - 3
J = (15 + nLen - i) Mod 6
sByte = Mid(sNum, i, 1)
If sByte <> "0" Then
If J = 1 Then sWord = sDigit10(sByte) Else sWord = sNumber(sByte) & sDigit(J)
BahtText = BahtText & sWord
End If
If J = 0 And i <> nLen - 3 Then BahtText = BahtText & "ล้าน": BahtText = Replace(BahtText, "หนึ่งล้าน", "เอ็ดล้าน")
Next
If Left(sNum, 1) = "1" Then BahtText = Replace(BahtText, "เอ็ดล้าน", "หนึ่งล้าน")
If Left(sNum, 2) = "11" Then BahtText = Replace(BahtText, "สิบหนึ่งล้าน", "สิบเอ็ดล้าน")
If Len(BahtText) > 0 Then BahtText = BahtText & "บาท"
If nLen > 4 Then BahtText = Replace(BahtText, "หนึ่งบาท", "เอ็ดบาท")
sNum = Right(sNum, 2)
If sNum = "00" Then
BahtText = BahtText & "ถ้วน"
Else
If Left(sNum, 1) <> "0" Then BahtText = BahtText & sDigit10(Left(sNum, 1))
If Right(sNum, 1) <> "0" Then BahtText = BahtText & sNumber(Right(sNum, 1))
BahtText = BahtText & "สตางค์"
If Left(sNum, 1) <> "0" Then BahtText = Replace(BahtText, "หนึ่งสตางค์", "เอ็ดสตางค์")
End If
End Function


หรือ ทำการ References Microsoft Excel 14.0 Object Library (ขึ้นอยู่กับ Version Excel ให้เครื่อง)
และทำการเรียกใช้ โดยใช้
คำสั่ง WorksheetFunction.BathText(Value)
และเราสามารถให้ Function อื่น ๆ ของ Excel ได้อีกด้วย



Good Luck

1 ความคิดเห็น:

 
Copyright © . DataJeda Computer Basic - Posts · Comments
Theme Template by DataJeda.com · Powered by DataJeda.com