excel - 遍历文件夹代码的下标超出范围

标签 excel vba

我正在尝试使用以下代码遍历文件夹。但是,我不断收到下标超出范围错误。谁能解释我能做些什么来解决这个问题?

Sub LoopThroughFolder()

    Const FileSpec As String = "*.xls"
    Dim y As Integer
    Dim MyFolder As String
    Dim MyFile As String
    Dim iDot As Integer
    Dim FileRoot As String
    Dim FileExt As String

    Dim ArrayData() As Variant


    For y = 2009 To 2030

        ReDim Preserve ArrayData(y, 12)
        MyFolder = ActiveWorkbook.Path & "\" & y & "\"

        i = 1
        MyFile = Dir(MyFolder & FileSpec)
        Do While Len(MyFile) > 0
            iDot = InStrRev(MyFile, ".")

            If iDot = 0 Then
                FileRoot = MyFile
                FileExt = ""
            Else
                FileRoot = Left(MyFile, iDot - 1)
                FileExt = Mid(MyFile, iDot - 1)
            End If

            MyFile = Dir
            ArrayData(y, i) = FileRoot
            MsgBox ArrayData(y, i)
            i = i + 1
        Loop

    Next y

End Sub

最佳答案

根据这个 msdn link , 你只能ReDim Preserve在数组的最后一个维度上,在您的情况下,您只能更改 12ReDim Preserve ArrayData(y, 12) .更改数组参数的顺序将解决此问题。

关于excel - 遍历文件夹代码的下标超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16074179/

相关文章:

vba - For循环删除行

excel - 根据单元格值选择工作表

vba - Excel VBA : Run-time error (Method 'Value' of object 'Range' failed), 但仅限连续运行

vba - 将函数结果复制到 Sub

Excel佣金公式

vba - Excel VBA 恢复我的空格键操作

excel - 如何使用 VBA 导出工作表按钮和详细信息

vba - 字符串中的子字符串

excel - Access VBA如何判断文件是否是Excel格式?

javascript - 使用 IE 导航时处理弹出窗口