JayyM
JayyM

Reputation: 155

How to add or subtract binary numbers using vba?

I have a data of 5-bits of binary numbers (10110, 10111, 01011, etc..), which are the data information of transmitted bits in the fiber. Now I happened to do is that I need to sum and subtract few binary numbers, and these are high in volume. So as I already have these data in my excel sheet, I was thinking of implementing VBA code to add and subtract the binary numbers. I couldn't find any function that sums 1+1=10, I'm just finding that 1+1=2. Also, to subtract, there's a method of 1's and 2's compliment. If there's something which can be done by VBA, kindly help me out. I have tried my best to code, but it sums 1+1=2. Thanks!

Upvotes: 2

Views: 2145

Answers (2)

Gary's Student
Gary's Student

Reputation: 96753

With 5-bit binaries in A1 and A2, in another cell enter:

=DEC2BIN(SUM(BIN2DEC(A1),BIN2DEC(A2)))

enter image description here

As you see, VBA is not required. If you really need VBA then:

Public Function BinSum(s1 As String, s2 As String) As String
    With Application.WorksheetFunction
        BinSum = .Dec2Bin(.Sum(.Bin2Dec(s1), .Bin2Dec(s2)))
    End With
End Function

Upvotes: 4

Nathan_Sav
Nathan_Sav

Reputation: 8531

Using VBA

worksheetfunction.DEC2BIN(worksheetfunction.BIN2DEC("0011") + worksheetfunction.BIN2DEC("0011"))

Upvotes: 2

Related Questions