打开多个工作簿时出现运行时错误 9

Runtime error 9 when opening several workbooks

我的代码的目标是打开几个工作簿供以后使用。

我创建了一个循环。第一个工作簿总是被打开。

在该循环的第二个实例中,我收到了

runtime error 9

用于:

file = Sheets("Start").Cells(i, 5) ' Get file name

在引用的单元格 (Cell (2, 5) 中,没有条目,所以我认为错误可能与此有关。我尝试创建 Skip (with GoTo),现在已被注释掉,因为我什至不知道它是否有效。

''  Open Workbooks--------------------------------------------------------
fromPath = Sheets("Start").Cells(1, 2) ' Get path from cells on Report tab

For i = 1 To 9

    ' Make sure there is a backslash at the end of the from path
    If Right(fromPath, 1) <> "\" Then fromPath = fromPath & "\"
   
    file = Sheets("Start").Cells(i, 5) ' Get file name
    'If file = "" Then
    '    GoTo SkipTheLoop: '' If Cell is empty
    'End If

    'Make sure there is a .xlsx at the end of the file name
    If Right(file, 5) <> ".xlsx" Then file = file & ".xlsx"

    Set wkbFrom = Workbooks.Open(fromPath & file) ' Open workbook by path and name
SkipTheLoop:
Next i

打开多个工作簿

小贴士

  • 使用 Option Explicit 强制您声明所有变量。
  • ThisWorkbook,包含此代码的工作簿。
  • 限定对象(wb.Worksheets...)。
  • 如果是工作表,则使用 Worksheet 而不是 Sheet
  • 如果它是来自单元格的值,则使用 ValueValue2
  • 使用On Error Resume Next时(延迟错误处理),使用一到两行,用On Error Goto 0关闭错误处理).
  • 请注意,previous 不是强制性的,没有它代码可能仍然有效。直到没有。
Option Explicit

Sub test()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim fromPath As String: fromPath = wb.Worksheets("Start").Cells(1, 2).Value
    
    Dim wkbFrom As Workbook
    Dim fName As String
    Dim i As Long, n As Long
    
    For i = 1 To 9
        If Right(fromPath, 1) <> "\" Then fromPath = fromPath & "\"
        fName = wb.WorkSheets("Start").Cells(i, 5).Value
        If Right(fName, 5) <> ".xlsx" Then fName = fName & ".xlsx"
        On Error Resume Next
        Set wkbFrom = Workbooks.Open(fromPath & fName)
        On Error GoTo 0
        If Not wkbFrom Is Nothing Then
            n = n + 1
            Set wkbFrom = Nothing
        End If
    Next i
    
    MsgBox n & " workbook(s) opened.", vbInformation, "Open Workbooks"
    
End Sub