How to convert a raw hex byte string to Long?

Viper7

New Member
Joined
Jul 1, 2011
Messages
8
Hello VBAers -

I am a VBA noob, so be patient.

I have an RS-232 device hooked up to my Win7 Excel 2010 spreadsheet leveraging the CommRead() and CommWrite() VBA functions I found on the web. The communication link works -- I can send VBA "Strings" of hex bytes to and from the device with my spreadsheet when "Buttons" are pressed.

The replies from our device come in as VBA "Strings" 4 hex bytes long.
So when the device sends me a 32 bit integer 1234567 decimal my VBA function gets a "String" of 4 non-printable hex bytes: 0x00 0x12 0xD6 and 0x87, which is 1234567 decimal.

I seek a VBA way to convert these bytes to the VBA "Long" integer.

Lots of VBA functions on the web appear to come close, but when I run them errors about Type Conversion incompatibility pop up. Some functions use Byte Arrays but I don't get how to convert from String to Byte Arrays with VBA.

Therefore, VBA tips to convert such a hex byte String to a Long would be appreciated.

Thanks in advance!
Viper
 
Hi

Another option:

Code:
Function Str2Lng(sInp As String) As Long
Str2Lng = "&H" & Right("0" & Hex(Asc(Mid(sInp, 1, 1))), 2) & Right("0" & Hex(Asc(Mid(sInp, 2, 1))), 2) & _
                 Right("0" & Hex(Asc(Mid(sInp, 3, 1))), 2) & Right("0" & Hex(Asc(Mid(sInp, 4, 1))), 2)
End Function
 
Upvote 0

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".

Forum statistics

Threads
1,224,564
Messages
6,179,547
Members
452,925
Latest member
duyvmex

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top