vb运行出现错误9,“下标越界”???
Private Sub MSComm1_OnComm()
Dim BytReceived() As Byte
Dim strBuff As Variant
Select Case MSComm1.CommEvent
Case 2
MSComm1.InputLen = 0
strBuff = MSComm1.Input
BytReceived() = strBuff
Dim i As Long
For i = 0 To UBound(BytReceived)
Debug.Print BytReceived(i)
Next
If i <= 2 Then
Text2 = BytReceived(0)
BytReceived(0) = 0
Else
tongyi = BytReceived(0)
BytReceived(0) = 0
fandui = BytReceived(2)
BytReceived(2) = 0
qiquan = BytReceived(4)
BytReceived(4) = 0
End If
End Select
我这段代码那里有问题 为什么运行时经常出现 错误9,“下标越界” 调试时总指在qiquan = BytReceived(4)这一行
我也从网上看了相关的资料,知道是数组方面的问题,但改了几次之后,还是一直有错误,希望可以在这里得到解决!!! --------------------编程问答-------------------- 如果发接收数据小于3个字节(1或2字节)时qiquan = BytReceived(4) 就越界!!! --------------------编程问答-------------------- 应该是接收为2个字节时候,此时
For i = 0 To UBound(BytReceived)'2个字节时,此值为3
Debug.Print BytReceived(i)
Next
'到此,i=4
If i <= 2 Then
'因为i=4,本段不执行
Text2 = BytReceived(0)
BytReceived(0) = 0
Else
'执行本段
tongyi = BytReceived(0)
BytReceived(0) = 0
fandui = BytReceived(2)
BytReceived(2) = 0
qiquan = BytReceived(4) '数组上限为3,越界产生
BytReceived(4) = 0
End If --------------------编程问答-------------------- 但是我下位机发送的代码为
SBUF=tongyi; //给上位机返回投票结果
while(!TI);
TI=0;
SBUF=fandui;
while(!TI);
TI=0;
SBUF=qiquan;
while(!TI);
TI=0;
所以说我每次都发送了3个字节的数据 如果是这样的错误我应该怎么该? --------------------编程问答-------------------- 既然你返回三个字节,你试试设置
Rthreshold =3
然后再测试你代码看看 --------------------编程问答-------------------- Rthreshold =3
还是不行。 --------------------编程问答-------------------- Rthreshold 不能等于3,因为我是分两次接收的 第一个是一位数据,第二次是两位数据 --------------------编程问答-------------------- 因为你每次接收的数据不同所以不能用固定的Index
你用4 ,但是数组最高就到3。自然下标就越界了。如果你非要用4的话家如下判断
--------------------编程问答-------------------- UBound(BytReceived) 调试一下接收了几个字节
if UBound(BytReceived)<4 then
redim preserve BytReceived(4)
end if
补充:VB , 控件