Reputation: 71
I am trying to convert a hex string to a decimal string, to input into an Excel spreadsheet, but I am having no luck finding any solutions to the problem. I can successfully display the hex string in Excel, but I want to convert it to a decimal string before pushing it to the Excel spreadsheet.
I have tried the following (also see code currently commented out):
Private Function ToHexString(ByRef buffer As Variant) As String
ReDim bytes(LBound(buffer) + 6 To LBound(buffer) + 9)
Dim i As Long
For i = LBound(buffer) + 6 To LBound(buffer) + 9
bytes(i) = Hex(buffer(i))
Next
ToHexString = Strings.Join(bytes, "")
End Function
Function FromHex(hexString As String) As Long
FromHex = Val("&H" & hexString)
End Function
Private Sub StrokeReader1_CommEvent(ByVal Evt As StrokeReaderLib.Event, ByVal data As Variant)
Select Case Evt
Case EVT_DISCONNECT
Debug.Print "Disconnected"
Case EVT_CONNECT
Debug.Print "Connected"
Case EVT_DATA
buf = StrokeReader1.Read(BINARY) 'Use BINARY to receive a byte array
Debug.Print ToHexString(buf)
' Debug.Print buf
' Debug.Print "myStr length: " & Len(buf)
'using `StrConv` to allow for 2-byte unicode character storage
' dist = Convert.ToInt32("c001", 16)
' ActiveSheet.Range("A1").Value = ToHexString(buf)
' int number = Convert.ToInt32(buf, 16);
'buf = "0081C"
' Dim i As Integer = Convert.ToInt32("c001", 16)
'hexDist = ToHexString(buf)
'distInt As Integer = Convert.ToInt32(hexDist, 16)
'decLong = FromHex(buf)
Dim hexVal As String
hexVal = ToHexString(buf)
Dim intVal As Integer
intVal = Convert.ToInt32(hexVal, 16)
ActiveCell.Value = intVal
ActiveCell.Offset(1, 0).Select
End Select
End Sub
The hex string typically looks like this: 00A57 and the decimal string output should look like this: 2647
I am getting Syntax errors or Error 402, depending on what I try to make work.
Upvotes: 0
Views: 1455
Reputation: 3670
Change the corresponding part of your code to:
Dim intVal as Long
intVal = FromHex(hexVal)
Upvotes: 1