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

时间:2018-04-18 00:56:39

标签: vba excel-vba filenames openfiledialog excel

我尝试使用我的代码打开所有选定的文件。但只有当第一条路径转到另一条路径时才会打开,错误"下标超出范围"弹出。

以下是我的代码:

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

还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

问题出在这一行:

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

希望有所帮助。

相关问题