尝试打开多个工作簿时下标超出范围错误

Subscript out of range error when trying to open multiple workbooks

我正在尝试使用我的代码打开所有选定的文件。但是转到另一条路径时只打开第一条路径,就弹出错误"Subscript out of range"。

下面是我的代码:

Sub Select_File_Click()
    Dim lngCount As Long
    Dim cl As Range
    Dim c2 As Range
    Dim ItemType As String

    Set cl = ActiveSheet.Cells(1, 3)
    ' Open the file dialog
    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True
        .Filters.Clear
        .Filters.Add "comma-separated values", "*.csv"
        .InitialFileName = "*" & ItemType & "*.*"
        .InitialView = msoFileDialogViewDetails
        .Show
        For lngCount = 1 To .SelectedItems.Count
            ' Add Hyperlinks
            cl.Worksheet.Hyperlinks.Add _
            Anchor:=cl, Address:=.SelectedItems(lngCount), _
                TextToDisplay:=.SelectedItems(lngCount)
            ' Add file name
            'cl.Offset(0, 1) = _
            '    Mid(.SelectedItems(lngCount), InStrRev(.SelectedItems(lngCount), "\") + 1)
            ' Add file as formula
            cl.Offset(0, 1).FormulaR1C1 = _
                 "=TRIM(RIGHT(SUBSTITUTE(RC[-1],""\"",REPT("" "",99)),99))"


            Set cl = cl.Offset(1, 0)
            Set c2 = cl.Offset(0, 1)
        Next lngCount
        Sheets(1).Cells(1, 1) = .SelectedItems.Count
    End With
End Sub

Sub All_data_Click()
    Dim Count As Integer
    Count = Sheets(1).Cells(1, 1)

    For i = 1 To Count
        pth = Sheets("Sheet1").Cells(i, 3).Value 'Select folder path
        Set LookupWB = Workbooks.Open(Filename:=pth)
    Next i
End Sub

还有其他方法吗?

问题出在这一行:

pth = Sheets("Sheet1").Cells(i, 3).Value

在 Excel 中打开第一个 CSV 文件后,它将成为活动工作簿。因此,当您调用 Sheets 时,它实际上指的是新打开的工作簿(即 CSV 文件),它没有名为 "Sheet1" 的 sheet,因此,下标范围错误。

您可以通过调用 ThisWorkbook.Sheets 来解决这个问题。 ThisWorkbook 属性 指的是承载当前 运行 VBA 代码的工作簿。所以,你的 All_data_Click 看起来像这样:

Sub All_data_Click()
    Dim Count As Integer
    Count = Sheets(1).Cells(1, 1)

    For i = 1 To Count
        pth = ThisWorkbook.Sheets("Sheet1").Cells(i, 3).Value 'Select folder path
        Set LookupWB = Workbooks.Open(Filename:=pth)
    Next i
End Sub

希望对您有所帮助。