简体   繁体   中英

Excel 2013 VBA - Runtime error 9: Subscript out of range

I'm new to VBA and did run into a problem I can't seem to find a solution to on my own -> so Your help is much appreciated :).

I'm getting "Run-time error 9: Subscript out of range" when attempting to run following code:

Dim i as Long, l as Long, x as Long, y as Long, z as Long, lastrow as Long

   '..some unrelevant code
   x = 2

   For y = 1 To lastrow Step 2: For i = y To lastrow Step 2: For z = 0 To 1

   '..do stuff

   If z = 0 Then

        Dim datarange As Variant
        Dim myvar As Double
        Dim comp As Double
        Dim lrow As Long
        Dim lcol As Long

        l = 0
        lrow = x
        datarange = Range("k" & x & ":" & "ab" & x + 1).Value
        For lcol = 11 To 28
            myvar = datarange(lrow, lcol)
            comp = datarange(lrow + 1, lcol)
            If comp > 1 Then
                If myvar > 1 Then
                l = l + 1
                End If
            Else: l = l + 1
            End If
        Next

   End If

   x = x + 1

   Next: Next: Next

   '..etc

I got to this point after implementing the code-part with grey background in effort to include following knowledge into my project: http://blogs.office.com/2008/10/03/what-is-the-fastest-way-to-scan-a-large-range-in-excel/ (third point "Use a variant type variable").

Thanks in advance!

If you'll pardon the expression, you've two-stepped out of the bounds of the array:)

The index numbers of the dataRange array are different then their row/column numbers. If you go to VB Editor, View, and the Locals window as you are stepping through the code (F8), you will see that the array is 1 to 2 by 1 to 18.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM