maleficent
maleficent

Reputation: 53

Convert string to binary in excel vba

This is my code where I try to convert string to binary but its not working.Can please somebody help me? I have been trying to solve this for past 5 days!! Thank you in advance!

  Sub Button1_Click()
          Dim strText As String
           strText = ActiveWorkbook.Sheets("Sheet2").Range("A1")

           Debug.Print strText
           Dim n, val As Integer
           n = Len(strText)

           Debug.Print n

           Dim str As String
            str = Mid(strText, 1, 1)
           Debug.Print str
           For i = 1 To n
           'val = CInt(strarr(i))
           val = Asc(str)

           Debug.Print val
           Dim bin As String
           Dim modval As Integer
           bin = ""

           While val > 0
           modval = val - (2 * (val \ 2))

           If modval = 1 Then
           bin = bin & "1"
           val = 0
           Else
           bin = bin & "0"
           val = 0
           End If
           Wend

           bin = StrReverse(bin)
           Debug.Print bin
           Next i
           Debug.Print i
            ActiveWorkbook.Sheets("Sheet2").Range("A2") = bin
        End Sub

Upvotes: 2

Views: 5522

Answers (1)

Scott Craner
Scott Craner

Reputation: 152505

Sub Button1_Click()
    Dim fullstr As String
    fullstr = ActiveWorkbook.Sheets("Sheet2").Range("A1")

    Dim bin As String
    bin = ""

    Dim j As Long
    For j = 1 To Len(fullstr)
        Dim str As String
        str = Mid$(fullstr, j, 1)

        Dim z As Double
        z = Asc(str)

        Dim i As Long
        For i = 7 To 0 Step -1
            Dim y As Double
            y = (2 ^ i)

            bin = bin & Int(((z / y) - Int(((z / y) / 2)) * 2))
        Next i
        bin = bin & " "
    Next j

    ActiveWorkbook.Sheets("Sheet2").Range("A2") = bin
End Sub

Upvotes: 2

Related Questions