2

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
4
  • Please be more specific. What is it doing that is incorrect? Does it error? If so, on which line does it error? Commented Dec 5, 2019 at 23:11
  • @ScottCraner It doesnt give any error but also doesnt give output. output is always 0 for whatever input.I want something like if input = "hey" then output will be output = "01101000 01100101 01111001" Commented Dec 5, 2019 at 23:12
  • you keep resetting bin and val inside the loop. that is why you get nothing. Commented Dec 5, 2019 at 23:21
  • 1
    vb-helper.com/howto_binary_to_text.html Commented Dec 5, 2019 at 23:22

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for the code. Is there a way to do the reverse? I mean from binary to string
That is a new question.
Thanks a lot. I could found a clue at this LINK
Thank you so much!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.