Hex to ascii conversion error in Excel VBA

2019-08-01 18:53发布

I have found below stated function for conversion of hex to text.It works fin for most of hex to text conversions but give abnormal result.

For example, hex value is:

050003d40201414c4552542d42656c6f772038353435206966204e462054726164657320666f722031352d3230206d696e75746573202c77617463682050414e49432050414e4943207570746f20353439332d2d383437360d0a0d0a53656c6c204549434845522061742032343931302e2e2e73746f706c6f7373732032353

Result i get on using hex2text Function = |

Correct Result should have been something like:

ALERT-Below 8545 if NF Trades for 15-20 minutes ,watch PANIC PANIC upto 5493--8476........

(Note: I used hex2ascii conversion website http://www.rapidtables.com/convert/number/hex-to-ascii.htm to obtain correct results)

My Hex2text Function is:

Public Function HexToText(text As Range) As String
    Dim i As Integer
    Dim DummyStr As String

    For i = 1 To Len(text) Step 2
       DummyStr = DummyStr & Chr(Val("&H" & (Mid(text, i, 2))))
       DoEvents
    Next i

    HexToText = DummyStr
End Function

1条回答
倾城 Initia
2楼-- · 2019-08-01 19:36

As Alex has stated, the first 6 bytes are causing the issue.

You could either start at the 13th character by changing the ForNext loop:

 For i = 13 To Len(text) Step 2

Or you could filter any characters with ASCII code lower than 32 out..

If Val("&H" & (Mid(Text, i, 2))) > 31 Then DummyStr = DummyStr & Chr(Val("&H" & (Mid(Text, i, 2))))

Or replace them with (for instance) a space..

If Val("&H" & (Mid(Text, i, 2))) > 31 Then 
   DummyStr = DummyStr & Chr(Val("&H" & (Mid(Text, i, 2))))
Else
   DummyStr = DummyStr & " "
End If
查看更多
登录 后发表回答