下标超出了For循环中使用的范围

时间:2020-04-23 05:45:29

标签: excel vba

在VBA中运行以下代码以调用数组中的excel单元,并在FOR循环中使用它进行计算,但出现“下标超出范围”错误

Sub nestedLoopFor()
  Dim i As Integer
  Dim j As Integer
  Dim Qty As Variant


    Dim Cap As Variant
      Qty = Range("C2:L2").Value 'call cells from 3rd row
      Cap = Range("B3:B7").Value 'call cells from 2nd column

      For i = 1 To 5
          For j = 1 To 10
          Cells(i + 2, j + 2).Value = WorksheetFunction.Min(Qty(j), Cap(i))
          Qty(j) = Qty(j) - Cells(i + 2, j + 2).Value
          Cap(i) = Cap(i) - Cells(i + 2, j + 2).Value
          Next
      Next

    End Sub

1 个答案:

答案 0 :(得分:0)

FYI数量和上限是二维数组,因此如果要访问其中一个元素,则需要提供两个索引。

public static int getValidGuess(Scanner get)
    {
       int num;

        System.out.print("Guess a number: --> ");
        num = get.nextInt();

        return num;
    } // getValidGuess end

    public static boolean displayGuessResults(int start, int end, int num)
    {
         int n1, n2;
         Random gen = new Random();

        n1 = gen.nextInt(99) + 1;
        n2 = gen.nextInt(99) + 1;



        if(n1 < n2)
        {
            start = n1;
            end = n2;
        } // if end
        else
        {
            start = n2;
            end = n1;
        } //else end

        if(num > start && num < end)
        {
            System.out.println("\nThe 2 random numbers are " + start +
                    " and " + end);
            System.out.println("Good Guess!");

            return true;
        }
        else if (num < start || num > end)
        {
            System.out.println("\nThe 2 random numbers are " + start +
                    " and " + end);
            System.out.println("Outside range.");

            return false;
        }


    } // displayGuessResults end