VBA程序:将数字转换成任意进制的数

2023-12-11 16:03:47 浏览数 (1)

标签:VBA

在forum.ozgrid.com中看到的一段程序,可以将数字转换成任意进制的数。

代码如下:

代码语言:javascript复制
Public Function Bas2Bas(Number As String, Optional ByVal FromBase As Byte = 10, Optional ByVal ToBase As Byte = 16) As String
 Const BaseDigits As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 Dim MyResult As String
 Dim dRemainder As Double
 Dim MyPlace As Byte
 Dim MyDigit As Byte
 Dim dValue As Double
 On Error Resume Next
 If Len(Number) > 15 Then GoTo Done
 
 Number = UCase(Number)
 If (ToBase < 2) Or (ToBase > 36) Then GoTo Done
 
 For MyPlace = 1 To Len(Number)
   For MyDigit = 0 To 36
     If MyDigit >= FromBase Then GoTo Done
     If Mid(BaseDigits, MyDigit   1, 1) = Mid(Number, MyPlace, 1) Then Exit For
   Next
   dValue = dValue   MyDigit * FromBase ^ (Len(Number) - MyPlace)
 Next
 
 Do
   dRemainder = dValue - (ToBase * Int((dValue / ToBase)))
   MyResult = Mid(BaseDigits, dRemainder   1, 1) & MyResult
   dValue = Int(dValue / ToBase)
 Loop While (dValue > 0)
Done:
 Bas2Bas = MyResult
End Function

这是一个自定义函数,默认是将一个十进制数转换为一个十六进制数,你可以将一个十进制数转换为8进制或你认为的其他进制,如3进制!可将一个八进制数转换成一个十六进制数。

你可以试试看!

0 人点赞