经过好长时间的钻研和摸索,终于成功地将硬件的串口数据发送到了Excel表格里。下面详细讲解将硬件串口数据发送到Excel里的方法。
首先,打开Excel代码编辑器,添加窗体,插入串口控件。
![4b9ac882b9fe624487890d1e45315d14.png](https://i-blog.csdnimg.cn/blog_migrate/af3c95c643934276711868aa60739197.jpeg)
接着,编写以下代码。
![560ceb69a215e7db5e29c867acf85ae4.png](https://i-blog.csdnimg.cn/blog_migrate/4d44fe561dc2bfa063e1f5daf7181194.jpeg)
Private Sub btn_Close_Click()
MSComm1.PortOpen = False
btn_Start.Enabled = True
btn_Close.Enabled = False
End Sub
Private Sub btn_exit_Click()
If MSComm1.PortOpen = True Then
MSComm1.PortOpen = False
End If
Unload UserForm1
End Sub
Private Sub btn_Start_Click()
iniMSComm
MSComm1.PortOpen = True
btn_Close.Enabled = True
btn_Start.Enabled = False
End Sub
Private Sub iniMSComm()
MSComm1.CommPort = 5
MSComm1.Settings = "115200,n,8,1"
MSComm1.RThreshold = 1
MSComm1.InputLen = 0
MSComm1.PortOpen = True
MSComm1.InputMode = comInputModeText
MSComm1.RTSEnable = True
MSComm1.InBufferCount = 0
End Sub
Private Sub MSComm1_OnComm()
Dim t1 As Long, com_string As String
Static i As Integer
t1 = Timer
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.RThreshold = 0
Do
DoEvents
Loop While Timer - t1 < 0.01
com_string = MSComm1.Input
MSComm1.RThreshold = 1
i = i + 1: If i > 255 Then i = 1
Application.Cells(3, i).Value = com_string
End Select
End Sub
Private Sub UserForm_Initialize()
iniMSComm
End Sub
然后,用串口模块连接好电路板和电脑,给电路板供电工作。
![f434a3b9c1068ec470f60ea86c948567.png](https://i-blog.csdnimg.cn/blog_migrate/a433d87e7c830794fc862162d39731fb.jpeg)
运行代码,就会看到串口信息在Excel里打印出来了。
![7dc2b201df773bef58a48032d3ea0a11.png](https://i-blog.csdnimg.cn/blog_migrate/dfd91fbb98020c05824b67bbc399b231.jpeg)
最后,把编号代码的Excel保存成xlsm 格式的文件,以后想用时,直接打开就可以。