如何将串口接收到的数据保存到excel文档
1.启动excel从:工具-->宏-->visual basic 编辑器,打开excel vba.
2.在thisworkbook上右单击鼠标选择插入--用户窗体
3.单击一下插入的窗体,单击菜单上的--工具--附加控件--选择microsoft communications control, version 6.0
4.在窗体上添加mscomm1,添加commandbutton1
5.单串口机子,短接rs232的2脚和3脚,双串口机子用232线连接两个串口,注意2、3线交叉,我这里以单串口短接举例。
6.复制以下代码到你的窗体里:
vb code
'vba代码
private sub commandbutton1_click()
mscomm1.output = "beg1end"
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 '收到 rthreshold定义的字符数1字节
mscomm1.rthreshold = 0
do
doevents
loop while timer - t1 < 0.1 '延时时间自己调整
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
'activeworkbook.saveas filename:="c:\d1.xls"
end sub
private sub inimscomm()
'on error resume next
'=====-----初始化通信串口-----=====
mscomm1.commport = 1 '使用 com1
mscomm1.settings = "9600,n,8,1" '9600 波特,无奇偶校验,8 位数据,一个停止位
mscomm1.portopen = true '打开端口
mscomm1.rthreshold = 1 '缓冲区有1个字节就产生oncomm事件
mscomm1.inputlen = 0 '为 0 时,使用 input 将使 mscomm 控件读取接收缓冲区中全部的内容。
mscomm1.inputmode = cominputmodetext 'input以二进制形式取回用cominputmodebinary,以文本形式取回是(缺省项)
mscomm1.rtsenable = true
mscomm1.inbuffercount = 0 '清空缓冲区
end sub
private sub userform_initialize()
inimscomm
end sub
7.双击thisworkbook,复制以下代码到窗体里:
vb code
'vba代码
private sub workbook_open()
userform1.show 0
'userform1.hide
end sub
8.保存文件并关闭excel,然后再打开你的文件,然后单击你窗体上的按钮看看。
9.这个程序是我为你特意做的,已经做过测试,sys2003 office2003。
10.如果excel中有数据输入,再去测试你的设置,注意com口号与波特率的设置。