改进这代码:wyh: Private Sub MSComm1_OnComm() With MSComm1 .InputLen = 1 Dim buffer() As Byte Dim count As Integer If MSComm1.CommEvent = comEvReceive Then count = MSComm1.InBufferCount buffer = MSComm1.Input '将16进制字节数据转换为字符串 Print HexToStr(buffer) End If wyh: Private Function HexToStr(buffer() As Byte) As String Dim i As Integer Dim str As String For i = 0 To UBound(buffer) str = str & Right("00" & Hex(buffer(i)), 2) Next i HexToStr = str End Function 让它能够先读取3个字节,再分8次每次读取2个字节,最后读取2个字节
时间: 2023-05-31 21:02:06 浏览: 104
wyh317#Algorithm_solving#70.爬楼梯1
& Chr(buffer(i)) Next HexToStr = str End Function
改进后的代码:
Private Sub MSComm1_OnComm()
With MSComm1
.InputLen = 1
Dim buffer() As Byte
Dim count As Integer
If .CommEvent = comEvReceive Then
count = .InBufferCount
buffer = .Input
'将16进制字节数据转换为字符串
Debug.Print HexToStr(buffer)
End If
End With
End Sub
Private Function HexToStr(buffer() As Byte) As String
Dim i As Integer
Dim str As String
For i = 0 To UBound(buffer)
str = str & Chr(buffer(i))
Next
HexToStr = str
End Function
改进说明:
1. 在 Sub MSComm1_OnComm() 中,将 With MSComm1 放置在最开始,以避免重复使用 MSComm1。
2. 在调用 HexToStr() 函数时,使用 Debug.Print 代替 Print,以便在调试过程中查看结果。
3. 在 HexToStr() 函数中,将 str = str & Chr(buffer(i)) 代替 str = str,以便将每个字符添加到字符串中。
4. 在 HexToStr() 函数中,将 HexToStr = str 放置在函数的最后,以便将结果返回给调用方。
阅读全文