Hex to ascii conversion error in Excel VBA

回眸只為那壹抹淺笑 提交于 2019-12-24 05:51:34

问题


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:


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


来源:https://stackoverflow.com/questions/41809267/hex-to-ascii-conversion-error-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!