2015-12-21 47 views
0

我完全不熟悉VBA,我正在嘗試使按鈕將十進制數轉換爲八進制和六進制。這是我寫的十進制到二進制的代碼,但我很難試圖將它做十進制到八進制/六進制。將小數轉換爲八進制/六進制的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

你想使用這個在MS-Excel中?你已經完成了像「DEC2OCT」這樣的功能。請參閱[此鏈接](https://support.office.com/en-nz/article/Convert-numbers-to-different-number-systems-880eeb52-6e90-4a9d-9e56-acaba6a27560#bmconverts_a_decimal_number_to_binary)瞭解更多信息。 –

+0

@JoelGeiser謝謝你,但我試圖做一個按鈕,當按下時,會出現一個窗口,要求用戶輸入一個數字。輸入號碼後,程序會顯示另一個窗口,顯示轉換後的號碼。 –

回答

0

爲什麼要重新發明輪子? Excel中有2個內置函數,DEC2BINDEC2OCT,兩者都可以從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 

一個典型的運行提供了輸出,如:

enter image description here

相關問題