表格数组下标超出范围

时间:2015-10-26 20:46:44

标签: arrays excel vba excel-vba

我正在创建一个宏,它将从较大的工作簿中选择工作表,将这些工作表移动并保存为新工作簿,然后转到下一组。

我创建了一个伪"阵列"带有起始值和结束值(由表索引号指定)。

我遇到超出范围的"下标"完成保存文件的部分之后,但在循环之前会出现错误,这将导致下一组工作表。

以下是我的代码。任何有关此错误的帮助都将不胜感激。

Dim Start As Integer
Dim Finish As Integer
Dim SR As Integer  
Dim SC As Integer
Dim ER As Integer
Dim EC As Integer
SR = 2
SC = 5
ER = 2
EC = 6
Start = Sheets("REF").Cells(SR, SC).Value
Finish = Sheets("REF").Cells(ER, EC).Value
Dim sheetArray() As Double
Dim i As Integer
Dim c As Integer
i = 0
c = Start
lastrow = Cells(100, SC).End(xlUp).Row

Do Until SR = lastrow

    Do Until c > Finish
        ReDim Preserve sheetarray (0 to i)
        i = i + 1
        c = c + 1
    Loop

    Sheets(sheetarray).Copy
    ActiveWorkbook.SaveAs Filename:= _ XXXXXXXXXXXXXXXXXX

    C = Start
    i = 0
    SR = SR + 1
    ER = ER + 1
Loop
编辑:美国中部16:35

目前,相关代码块通过行lastrow = Cells(100, SC).End(xlUp).Row

与上述内容匹配

直到SR = lastrow

ReDim sheetArray(i)

Do Until c > Finish
    ReDim Preserve sheetArray(i)
    sheetArray(i) = c
    i = i + 1
    c = c + 1

Loop



Sheets(sheetArray).Copy
ActiveWorkbook.SaveAs Filename:= _
    XXXXXXXXXXXXX

c = Start
i = 0
SR = SR + 1
ER = ER + 1

Loop

2 个答案:

答案 0 :(得分:0)

这里你需要三件事:

  1. 在加载每个工作表索引之前重新调整数组,因为现在它的方式只会继续构建每个循环,因此从第二个循环开始会出现Subscript out of range错误 - 因为数组基本上有例如,1 3 5从第一个开始,然后是1 3 5 3 7,首先是1 3 5,第二个是3 7
  2. 每次设置数组的值。您只需设置数组的元素
  3. 限定从哪个工作簿复制工作表,因为每次复制工作表时,它都会将活动工作簿设置为新复制的工作簿。
  4. 像这样构建Do Loop块:

    Do Until SR = lastrow
    
        ReDim sheetArray(0) 'or you can put i here since you set it to zero at the bottom
    
        Do Until c > Finish
    
            ReDim Preserve sheetArray(i)
            sheetArray(i) = c
    
            i = i + 1
            c = c + 1
    
        Loop
    
        Workbooks("myWkb").Sheets(sheetArray).Copy 'where myWkb is the workbook name you need ... you can also use ThisWorkbook (meaning the workbook where the code is running) but this is not best practice
        ActiveWorkbook.SaveAs Filename:="XXXXXXXXXXXXXXXXXX"
    
        c = Start
        i = 0
        SR = SR + 1
        ER = ER + 1
    
    Loop
    

答案 1 :(得分:0)

正如我所看到的,问题是你只是在调整sheetArray的尺寸,但你没有把任何东西放进去。所以基本上,数组中的值都是零。然后,您要求Excel复制工作表(0),这超出了范围,因为工作表编号从1开始。

您可以通过在数组中写入要复制的工作表的索引来解决此问题:

Do Until c > Finish
    ReDim Preserve sheetarray (0 to i)
    sheetarray(i) = c ' <~~~~ or something else, according to your goal
    i = i + 1
    c = c + 1
Loop

ps:最好使sheetArray成为一个Integer(而不是Double)数组,因为它的元素是工作表的索引......但是,即使有双精度数,它也应该可以正常设置数组的内容。