简体   繁体   中英

Excel VBA: Giving array values as 'for loop' limits

I am facing 'Compile error: Syntax error' when I run the following code:

c_bound_h() is an array with indices from 0 to j. Lets assume the value of j is 3 (for this example) and the values in it are given below. The data in the sheet's rows is sorted according to these limits. eg from row2 till row1507 = 'Value 1', row 1508 till row3013 = 'Value 2', and so on.

I want to loop through each class of data, by passing these limits in the For loop. But, it is giving syntax error.

j = 3

c_bound_h(0) = 2
c_bound_h(1) = 1508
c_bound_h(2) = 3014
c_bound_h(3) = 4519

'I want to loop through each class of data, by passing these limits in the For loop. But, it is giving syntax error.

For L = 0 To j

    For c_bound_h(L) To c_bound_h(L+1)-1

Next L

Modify code as follows:

For L = 0 To j

    For K= c_bound_h(L) To c_bound_h(L+1)-1
    Next K

Next L

Use For L = 1 to J-1....

Because c_bound_h(L+1) would otherwise be out of bounds

Are you declaring c_bound_h as an integer?

I put this code into a workbook and it works perfectly fine for me :-

Sub test()

j = 3

Dim c_bound_h(4) As Integer

c_bound_h(0) = 2
c_bound_h(1) = 1508
c_bound_h(2) = 3014
c_bound_h(3) = 4519


For L = 0 To j

    For k = c_bound_h(L) To c_bound_h(L + 1) - 1
        MsgBox ("pass")
    Next k

Next L



End Sub

Need to prevent unneccessary loops by comparing 2 values at a time, but not going over the array limits. This is based on 'Don Relentless' code, but modified slightly.

Sub test()

j = 3

Dim c_bound_h(0 to 3) As Integer

c_bound_h(0) = 2
c_bound_h(1) = 1508
c_bound_h(2) = 3014
c_bound_h(3) = 4519

For L = 1 To j

    For k = c_bound_h(L-1) To c_bound_h(L) - 1
        debug.print "pass row " & k
    Next k

Next L

End Sub

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