该程序分析一个Excel报表,共有1000多行,每次都是读到54行时,下标越界,但是用程序中断查看,上一次循环的下标值都是1,12,不可能越界出错语句如下:strquantity(k, j) = strquantity(k, j) + yquantity 
提示strquantity(k, j) sbb    Dim strdevice() As String
    Dim strquantity() As Long
    ReDim strdevice(0) As String
    
    Dim i As Long
    Dim j As Long
    Dim k As Long
    Dim position As Long
    Dim deviceInList As Boolean
    deviceInList = False
    Dim flag As Integer
    flag = -2
        
    Dim xdevice As String 'xdevice的初始值是Excel中的E6
    Dim yquantity As Long
    xdevice = myworksheet.Cells(6, 5).Value
    
    i = 6
    flag = StrComp(xdevice, "")
    Do Until flag = 0
        For k = 0 To UBound(strdevice)
            If Trim(xdevice) Like Trim(strdevice(k)) Then
                deviceInList = True
                Exit For
            End If
        Next k
        
        If Not deviceInList Then
            ReDim Preserve strdevice(k) As String
            ReDim Preserve strquantity(k, 12 To 26) As Long
            strdevice(k) = xdevice
        End If
        
        For j = 12 To 26
            yquantity = myworksheet.Cells(i, j).Value
            If Not (yquantity Like "") Then
                strquantity(k, j) = strquantity(k, j) + yquantity 
            End If
        Next j
        
        i = i + 1
        xdevice = myworksheet.Cells(i, 5).Value
        flag = StrComp(xdevice, "")
         Loop

解决方案 »

  1.   

    实在无法调试你的代码,注释又很少,所以只能“瞎猜”了:你看一下,ReDim Preserve strquantity(k, 12 To 26) As Long 一句中K的值是多少!
      

  2.   

    跟踪下
    可能是你的K值通过
    For k = 0 To UBound(strdevice)
    If Trim(xdevice) Like Trim(strdevice(k)) Then
    deviceInList = True
    Exit For
    End If
    Next k
    这个过程发生了变化
      

  3.   

    又看了一下,发现也许犯了一个很低级的错误,deviceinlist 标志没有复位,
    回去再run一下看看
      

  4.   

    If Not deviceInList Then
                ReDim Preserve strdevice(ubound(strdevice)+1) As String
                ReDim Preserve strquantity(ubound(strdevice)+1, 12 To 26) As Long
                strdevice(ubound(strdevice)+1) = xdevice
            End If
      

  5.   

    ReDim Preserve strquantity(k, 12 To 26) As Long
    ReDim Preserve 只能定义动态数组的最后一维!你这是定义第一维,是不行的
    如:redim preserve s(1,i)
    redim preserve s(1,i+1)
      

  6.   

    ReDim Preserve strquantity(k, 12 To 26) As Long低维不可以redim得
      

  7.   

    感谢大家的热心帮助:
    问题的root cause是deviceinlist没有归位,而且,确实如各位所说的,只有最后一维可以动态改变大小,所以在作的时候,要把x,y方向的循环倒过来做,即外层循环是x方向的,内层循环是y方向的