Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba ReDim保留在For循环中_Vba_Excel - Fatal编程技术网

Vba ReDim保留在For循环中

Vba ReDim保留在For循环中,vba,excel,Vba,Excel,我不知道我做错了什么,因为下面的代码能够ReDim保留第一次迭代,但不能保留第二次迭代 Dim inj0() As Variant Dim i As Integer Dim c As Integer Dim Rng As Range Dim pos As Integer 'Find the last used column in a Row Dim LastCol As Integer With ActiveSheet LastCol = .Cells(2, .Columns.Coun

我不知道我做错了什么,因为下面的代码能够
ReDim保留第一次迭代,但不能保留第二次迭代

Dim inj0() As Variant
Dim i As Integer
Dim c As Integer
Dim Rng As Range
Dim pos As Integer

'Find the last used column in a Row
Dim LastCol As Integer
With ActiveSheet
    LastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
End With

c = 0
For i = 1 To LastCol
    pos = InStr(Cells(2, i), "80")
    If pos = 1 Then
        ReDim Preserve inj0(c, 2)
        inj0(0, 1) = "80"
        Set Rng = Cells(2, i)
        inj0(c, 2) = Rng.Offset(-1, 0).Value
        inj0(c, 0) = Rng.Offset(3, 0).Value
        c = c + 1
    End If
Next

尝试按如下方式更改代码:

c = 0
ReDim inj0(2, 0)
inj0(1, 0) = "80"
For i = 1 To LastCol
    pos = InStr(Cells(2, i), "80")
    If pos = 1 Then
        ReDim Preserve inj0(2, c)
        Set Rng = Cells(2, i)
        inj0(2, c) = Rng.Offset(-1, 0).Value
        inj0(0, c) = Rng.Offset(3, 0).Value
        c = c + 1
    End If
Next

如果您需要交换维度,最后您可以。

哪里会出现错误?在
ReDim Preserve inj0(c,2)
它说下标超出范围,您只能
ReDim Preserve
数组的最后一个维度。从在线帮助中,如果您使用保留关键字,您可以只调整最后一个数组维度,并且不能更改在这里考虑的一个优化的可能副本的维数。避免使用Redim Preserve,这是一项成本高昂的操作。相反,先确定需要多少个条目,然后定义大小,然后填充数组。比如先做一个CountIf来确定需要多少个条目会更好,特别是当有大量数据添加到数组中时。