【问题标题】:Subscript out of range error when trying to open multiple workbooks尝试打开多个工作簿时出现下标超出范围错误
【发布时间】:2018-04-18 00:56:38
【问题描述】:

我正在尝试使用我的代码打开所有选定的文件。但是只打开了第一个路径,当它转到另一个路径时,会弹出错误“下标超出范围”。

下面是我的代码:

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

还有其他方法吗?

【问题讨论】:

    标签: vba excel filenames openfiledialog


    【解决方案1】:

    问题出在这一行:

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

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

    您可以通过调用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
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多