本人做了一个用API函数通讯的程序,发送函数如下。如果去掉If Len(COMString) > 255 Then...End if之间的几句话,就会出现错误。还有bRead(LenVal) = Asc(Mid$(COMString, LenVal + 1, 1))中Mid$改为Mid也会出现错误,哪位高手给解释一下。注:每次发送数据不会超过20字符
Function WriteCommString(ByVal COMString As String) As Boolean
On Error GoTo handelwritelpt
Dim LenVal, SendBytes As Long
Dim retval As Long
Dim bRead(255) As Byte
If Len(COMString) > 255 Then
retval = WriteCommString(Left$(COMString, 255))
retval = WriteCommString(Right$(COMString, Len(COMString) - 255))
Exit Function
End If
For LenVal = 0 To Len(COMString) - 1
bRead(LenVal) = Asc(Mid$(COMString, LenVal + 1, 1))
Next LenVal
retval = WriteFile(CommHand, bRead(0), Len(COMString), SendBytes, 0)
If retval = 0 Then
retval = GetLastError()
MsgBox "串口发送数据错误: " & retval
CloseComm
WriteCommString = False
Exit Function
End If
WriteCommString = true
Exit Function
handelwritelpt:
WriteCommString = False
CloseComm
Exit Function
End Function
Function WriteCommString(ByVal COMString As String) As Boolean
On Error GoTo handelwritelpt
Dim LenVal, SendBytes As Long
Dim retval As Long
Dim bRead(255) As Byte
If Len(COMString) > 255 Then
retval = WriteCommString(Left$(COMString, 255))
retval = WriteCommString(Right$(COMString, Len(COMString) - 255))
Exit Function
End If
For LenVal = 0 To Len(COMString) - 1
bRead(LenVal) = Asc(Mid$(COMString, LenVal + 1, 1))
Next LenVal
retval = WriteFile(CommHand, bRead(0), Len(COMString), SendBytes, 0)
If retval = 0 Then
retval = GetLastError()
MsgBox "串口发送数据错误: " & retval
CloseComm
WriteCommString = False
Exit Function
End If
WriteCommString = true
Exit Function
handelwritelpt:
WriteCommString = False
CloseComm
Exit Function
End Function
解决方案 »
- 小弟的一个烂vb程序,希望哪位大哥可以看一看帮小弟解决,小弟不胜感激。
- 怎样用webbrowser修改网页源码?
- 如果过滤重复内容!
- 如何在SQL数据库中通过VB编程实现存储照片等图片呢?哪位达人能说一下原理?
- 请求大家帮个忙.用C++6.0串口API写个win32的DLL,我想在VB中调用.在线等.谢谢大家了.
- 如何使用ADO控件对Access数据库进行查询?
- c++学习
- 用VC编的DLL接口要符合什么要求才能供VB调用?
- vb的几个小问题
- 求助,vb 使用变量连结acess数据库查询问题
- 为什么一新建文档, 这段VBA代码就会停止?
- VB怎么把access数据库的表导出来存放发到CSV文件
你说的那个 If块,是限定每次发送字符串长度的(因为它是用固定大小的缓冲区)。
如果你发送的字符串那么少,那个If语句不会有作用。Mid$( ) 改为 Mid( ) 也“会出错”,同样无法解释。
用Mid$( )自然要比用 Mid( ) 好。
即使改成 Mid( ),在 Asc( )函数中, Mid( )的结果也会自动进行类型转换,参数也是合法的,怎么会引起错误!
有汉字(或其它 非ASCII码的字符)时, bRead(LenVal) = Asc( .... ) 那儿会出错。