You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何复制关闭工作簿的所有工作表至当前工作簿?代码报错索引越界

问题分析

你遇到的“索引越界9”错误,核心原因是Workbooks(currentCell.Value)的用法错误:Workbooks集合仅包含已打开的工作簿,且只能通过工作簿的**名称(不含路径)**或序号来索引。而你单元格中存储的是完整文件路径,用它去Workbooks集合里查找,自然找不到对应工作簿,触发索引越界错误。要操作处于关闭状态的工作簿,必须先通过路径将其打开。

修改后的VBA代码

Sub copy_Ws()
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim sourceWb As Workbook
    Dim sh As Worksheet: Set sh = wb.Worksheets(1)
    Dim cell As Range: Set cell = sh.Range("C1:C50")
    Dim currentCell As Range
    Dim filePath As String
    
    For Each currentCell In cell
        filePath = currentCell.Value
        ' 跳过空单元格、无效路径
        If filePath <> "" And Dir(filePath) <> "" Then
            On Error Resume Next
            ' 打开关闭的工作簿
            Set sourceWb = Workbooks.Open(filePath)
            ' 检查是否成功打开
            If Not sourceWb Is Nothing Then
                ' 复制所有工作表到当前工作簿末尾
                For Each ws In sourceWb.Sheets
                    ws.Copy After:=wb.Sheets(wb.Sheets.Count)
                Next ws
                ' 关闭源工作簿,不保存任何修改
                sourceWb.Close SaveChanges:=False
                Set sourceWb = Nothing
            End If
            On Error GoTo 0
        End If
    Next currentCell
End Sub

关键说明

  • 使用Workbooks.Open(filePath)直接通过完整路径打开关闭的工作簿
  • 加入Dir(filePath) <> ""判断,提前过滤不存在的文件路径,减少错误触发
  • 增加打开成功的判断,避免因文件损坏/权限问题导致后续代码报错
  • 复制完成后关闭源工作簿并设置sourceWb = Nothing,释放资源,避免内存占用

内容的提问来源于stack exchange,提问作者yusuf29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 14:21:06