提问者:小点点

如何将串行端口(例如COM 3)的输入读入Excel文件(十六进制)?


我正在将一组字节从外部设备推送到 COM 端口。生成的输入需要放在 Excel 中的单元格中,并转换为十六进制。我已经尝试了各种工具集,但没有一个在Excel中显示任何结果。

我试过一些VBA扩展,但他们都是付费的,也试过一些终端工具。当前的VBA工具代码如下所示。我也不能让它在excel单元格中显示任何内容。结果只显示在即时记录器中。

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(Text))  'Use BINARY to receive a byte array
        Debug.Print buf
  End Select
End Sub

'Use this to connect and set the port properties from the code
Sub connect()
  StrokeReader1.Port = 3
  StrokeReader1.BaudRate = 19200
  StrokeReader1.PARITY = NOPARITY
  StrokeReader1.STOPBITS = ONESTOPBIT
  StrokeReader1.DsrFlow = False
  StrokeReader1.CtsFlow = False
  StrokeReader1.DTR = False
  StrokeReader1.RTS = False
  StrokeReader1.Connected = True
  If StrokeReader1.Error Then
    Debug.Print StrokeReader1.ErrorDescription
  End If
End Sub

'Use this to send data to the remote device
Sub send()
  StrokeReader1.send "ABCD"  'A text string

  Dim x(3) As Byte  'A byte array
  x(1) = 1
  x(2) = 2
  x(3) = 3
  StrokeReader1.send x
End Sub

预期结果:< code > AA 00 00 22 00 03 00 00 03 2B 01 E1 35

实际结果:< code >?$ $


共1个答案

匿名用户

Case EVT_DATA
    buf = (StrokeReader1.Read(Text))  'Use BINARY to receive a byte array
    Debug.Print buf

你得到一个字节数组,就VBA而言,它与字符串没有区别-这是Debug. print buf没有抛出类型不匹配错误的唯一原因-因为任何其他数组根本无法将自己表示为字符串,因此您无法调试打印数组。

您需要的是迭代数组中的字节,使用< code>Hex函数获取每个字节的十六进制表示,并将它们连接成一个易读的字符串。

像这样:

Private Function ToHexString(ByRef buffer As Variant) As String
'note: buffer array is wrapped in a Variant, could be passed ByVal

    'first allocate/size a dynamic array to hold our results;
    'by sizing from LBound(buffer) to UBound(buffer), we get
    'an array that's sized exactly the same as the buffer array.
    ReDim bytes(LBound(buffer) To UBound(buffer))

    'now iterate all items in the array
    Dim i As Long
    For i = LBound(buffer) To UBound(buffer)
        'store the hex representation of the byte at index i into our hex-bytes array
        bytes(i) = Hex(buffer(i))
    Next

    'return the joined hex-bytes array, using a space to separate the individual hex-bytes
    ToHexString = Strings.Join(bytes, " ")

End Function

现在您可以执行Debug.PrintToHexString(buf),这应该会产生预期的输出。

如果您希望输出到单元格,您需要从特定的< code >工作表中获取一个< code>Range对象。例如,如果您要写入任何活动工作表的单元格A1:

ActiveSheet.Range("A1").Value = ToHexString(buf)

或者

ActiveSheet.Cells(1, 1).Value = ToHexString(buf)