在Visual Basic for Applications(Excel)中将十六进制字符串转换为十进制字符串

时间:2019-07-07 09:00:45

标签: vba hex decimal

我正在尝试将十六进制字符串转换为十进制字符串,以输入到Excel电子表格中,但是我没有运气找到该问题的任何解决方案。我可以在Excel中成功显示十六进制字符串,但我想先将其转换为十进制字符串,然后再将其推入Excel电子表格。

我尝试了以下操作(另请参见当前注释掉的代码):

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

十六进制字符串通常如下所示:00A57 和十进制字符串输出应如下所示:2647

我遇到语法错误或错误402,具体取决于我尝试执行的工作。

1 个答案:

答案 0 :(得分:1)

将代码的相应部分更改为:

\[img\](https?://.*\.(?:jpe?g|gif|png|bmp).*)\[/img\]