Option Explicit
Const sBaseStr As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx"
Function MaHoaSo(ByVal iStr As String, Optional bMaHoa As Boolean = True, Optional iBase As String = sBaseStr) As String
'Function MaHoaSo: Chuyen So iStr thanh Ma hoac chuyen Ma iStr thanh So
'bMaHoa: Mac dinh = True chuyen So thanh Ma, bMaHoa = False chuyen Ma thanh So
'iBase: Chuoi cac ky tu Ma Hoa, Mac dinh = sBaseStr
If bMaHoa = True Then
MaHoaSo = MaHoa(iStr, iBase)
Else
MaHoaSo = GiaiMa(iStr, iBase)
End If
End Function
Function MaHoa(ByVal iNum As String, Optional iBase As String = sBaseStr) As String
Dim j&, div&, tmp$, imod$, Res$
'Function MaHoa: Chuyen So iNum thanh Ma
'iBase: Chuoi cac ky tu Ma Hoa, Mac dinh = sBaseStr
div = Len(iBase)
Do While iNum <> Empty
tmp = Empty: imod = Empty
For j = 1 To Len(iNum)
imod = imod & Mid(iNum, j, 1)
If CLng(imod) >= div Then
tmp = tmp & Int(imod / div)
imod = imod - Int(imod / div) * div
Else
If tmp <> Empty Then tmp = tmp & "0"
End If
Next j
iNum = tmp
Res = Mid(iBase, imod + 1, 1) & Res
Loop
MaHoa = Res
End Function
Function GiaiMa(ByVal iCode As String, Optional iBase As String = sBaseStr) As String
Dim mul&, k&, j&, inter&, t&, tmp$, Res$
'Function GiaiMa: Chuyen Ma iCode thanh So
'iBase: Chuoi cac ky tu Ma Hoa, Mac dinh = sBaseStr
If Len(iCode) = 0 Then Exit Function
mul = Len(iBase)
Res = InStr(1, iBase, Mid(iCode, 1, 1), vbBinaryCompare) - 1
For k = 2 To Len(iCode)
inter = Empty: tmp = Empty
For j = Len(Res) To 1 Step -1
t = Mid(Res, j, 1) * mul + inter
If j = Len(Res) Then t = t + InStr(1, iBase, Mid(iCode, k, 1), vbBinaryCompare) - 1
inter = Int(t / 10)
tmp = (t Mod 10) & tmp
Next j
Res = inter & tmp
Next k
GiaiMa = Res
End Function