日期:2014-05-20 浏览次数:20881 次
'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