我是VBA的新手,我正在尝试将一个十进制数转换为八进制和六进制。这是我为十进制编写的二进制代码,但我很难尝试将十进制数转换为八进制/十六进制。
Private Sub Conversion_Click()
ActiveSheet.Cells.Clear 'Supprime toutes les valeurs qui étaient auparavant sur la feuille
If (IsNumeric(ConversionInt.NbText)) Then 'Vérifie que le texte est bien un nombre entier et non une chaine de caractères
If (Int(ConversionInt.NbText) / ConversionInt.NbText = 1) Then
ConversionInt.Hide 'Cache le formulaire conversion
Call Division(ConversionInt.NbText) 'Effectue la division sur le nombre demandé
Else: MsgBox "Vous devez rentrer un nombre entier"
End If
Else
MsgBox "Vous devez rentrer un nombre entier" 'Message d'erreur si on a pas un nombre entier
End If
End Sub
如果有人可以提供帮助,那就太过分了,谢谢。
答案 0 :(得分:0)
为什么重新发明轮子? Excel有两个内置函数DEC2BIN
和DEC2OCT
,这两个函数都可以在VBA中使用:
Sub test()
Debug.Print Application.WorksheetFunction.Dec2Hex(123456)
End Sub
在即时窗口中打印1E240
Excel还有一个函数DEC2BIN
,由于某种原因,它不接受大于511的输入。您可以使用两步法 - 首先使用DEC2HEX
然后转换每个十六进制数字到二进制:
Function Convert(num As Variant, num_base As Long) As Variant
Dim s As String, i As Long
With Application.WorksheetFunction
Select Case num_base
Case 16:
Convert = .Dec2Hex(num)
Case 8:
Convert = .Dec2Oct(num)
Case 2:
s = .Dec2Hex(num)
Convert = .Hex2Bin(Mid(s, 1, 1))
For i = 2 To Len(s)
Convert = Convert & .Hex2Bin(Mid(s, i, 1), 4)
Next i
Case Else:
Convert = CVErr(xlErrValue)
End Select
End With
End Function
像这样测试:
Sub test()
Dim s As String
s = InputBox("Enter a number")
MsgBox s & " is" & vbCrLf & _
Convert(s, 2) & " in binary" & vbCrLf & _
Convert(s, 8) & " in octal" & vbCrLf & _
Convert(s, 16) & " in hex" & vbCrLf
End Sub
典型的运行提供如下输出:
答案 1 :(得分:0)
如果您想重新发明轮子,这里是轮子。 此函数从十进制转换为另一个数字系统。 此功能与Excel功能相同。
Function cn(ByVal n As Double, ByVal s As Double)
'n the number to convert
's the numberic system to convert to.
'This function can convert to binary all the way to the length of the
'digits string and all in between.
Dim x As Double 'The exponent without decimals
Dim xx As Double 'The exponent with decimals, if any
Dim r As String 'The return string
Dim p As Integer 'Posistion of the digit in the return string
Dim L As Long 'Length of the string return string
Dim d '(d+1) because mid() does not accept 0.
'The position of the digit in the digits string.
Dim v As Double 'The numeric value of the position
'of the digit in the return string
Dim digits As String
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Start:
If n > 0 Then
xx = Log(n) / Log(s)
x = Int(xx)
End If
p = x + 1
If r = "" Then
r = String(p, "0")
L = p
End If
v = s ^ x
d = n \ v
Mid(r, L - x, 1) = Mid(digits, d + 1, 1)
n = n - (v * d)
If n <> 0 Then GoTo Start
cn = r
End Function