经过好长时间的钻研和摸索,终于成功地将硬件的串口数据发送到了Excel表格里。下面详细讲解将硬件串口数据发送到Excel里的方法。
首先,打开Excel代码编辑器,添加窗体,插入串口控件。
接着,编写以下代码。
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
然后,用串口模块连接好电路板和电脑,给电路板供电工作。
运行代码,就会看到串口信息在Excel里打印出来了。
最后,把编号代码的Excel保存成xlsm 格式的文件,以后想用时,直接打开就可以。
,