VB Function to Format Roman Numerals (Visual Basic/VBasic/VBA)

VB Function to Format Roman Numerals

The function below can be used to convert integers into Roman numerals.



' Formats a number as a roman numeral.
' Author: Christian d'Heureuse (www.source-code.biz)
Public Function FormatRoman(ByVal n As Integer) As String
 If n = 0 Then FormatRoman = "0": Exit Function
 ' There is no roman symbol for 0, but we don't want to return an empty string.
 Const r = "IVXLCDM" ' roman symbols
 Dim i As Integer: i = Abs(n)
 Dim s As String, p As Integer
 For p = 1 To 5 Step 2
 Dim d As Integer: d = i Mod 10: i = i \ 10
 Select Case d ' format a decimal digit
 Case 0 To 3: s = String(d, Mid(r, p, 1)) & s
 Case 4: s = Mid(r, p, 2) & s
 Case 5 To 8: s = Mid(r, p + 1, 1) & String(d - 5, Mid(r, p, 1)) & s
 Case 9: s = Mid(r, p, 1) & Mid(r, p + 2, 1) & s
 End Select
 Next
 s = String(i, "M") & s ' format thousands
 If n < 0 Then s = "-" & s ' insert sign if negative (non-standard)
 FormatRoman = s
 End Function


Test routine:

' Writes a list of roman numerals into a text file.
' The output can be used as a "decimal to roman" conversion table.
Public Sub PrintToFile(ByVal FileName, Optional ByVal First = 1, Optional ByVal Last = 2100)
 Dim fh: fh = FreeFile
 Open FileName For Output As fh
 Dim i As Integer
 For i = First To Last
 Print #fh, i & " = " & FormatRoman(i)
 Next
 Close #fh
 End Sub


Author: Christian d'Heureuse (www.source-code.biz, www.inventec.ch/chdh)
License: Free / LGPL
Index

AltStyle によって変換されたページ (->オリジナル) /