Home » excel » excel – dec2bin doesnt work as per expectation when called through VBA

excel – dec2bin doesnt work as per expectation when called through VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

Excel has this function dec2bin(num,places) which works well. But when I use it in VBA, I get the result, but format gets off the hook if msb and following bits are 0.

I wish to obtain:

0001 instead of 1

0101 instead of 101

This I observe when I redirect it to the spreadsheet:

Range("I2").Value = Mid(y, 2, 3)

If I store it in a variable and try to access the bits I get it right, but it’s no use if I can’t put it in spreadsheet the above mentioned way.

Any ideas how to resolve this?

How to&Answers:

Try

Sub Sample()
    Dim sVal As String

    sVal = Application.Evaluate("=DEC2BIN(7, 4)")

    Debug.Print sVal
End Sub

Or if you do not want to hardcode the Places then use this

Sub Sample()
    Dim sVal As String
    Dim nPlace  as Long

    nPlace = 4

    sVal = Application.Evaluate("=DEC2BIN(7," & nPlace & ")")

    Debug.Print sVal
End Sub

This will give you 0111 and not 111

EDIT

If you want to output it to an excel cell then you have two options

A) Format the cell as text and then use

Sub Sample()
    Dim sVal As String
    Dim nPlace As Long

    '~~> Number of places
    nPlace = 4

    sVal = Application.Evaluate("=DEC2BIN(7," & nPlace & ")")

    ThisWorkbook.Sheets("Sheet1").Range("A1").Value = sVal
End Sub

Alternatively you could use .Numberformat to format the cell via code.

OR

B) Use ' before inputting the data in Excel

Sub Sample()
    Dim sVal As String
    Dim nPlace As Long

    '~~> Number of places
    nPlace = 4

    sVal = Application.Evaluate("=DEC2BIN(7," & nPlace & ")")

    ThisWorkbook.Sheets("Sheet1").Range("A2").Value = "'" & sVal
End Sub