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

VBA执行tB.Sheets(ShName).Copy时出现下标越界错误求助

解决VBA中tB.Sheets(ShName).Copy的下标越界错误

下标越界的核心原因是ShName对应的工作表不存在于目标工作簿tB中,或是ShName本身的值无效,以下是针对性的排查和解决方法:

  • 检查单元格内容有效性
    你的代码遍历D3:E28的每个单元格,将单元格值作为工作表名使用。如果单元格是空值、包含斜杠/问号等工作表名不允许的特殊字符,或是对应的工作表根本不存在,就会触发错误。
    可以在代码中加入校验逻辑,跳过无效内容:

    For Each cell In Row
        ' 跳过空单元格
        If cell.Value = "" Then Continue For
        ' 验证工作表是否存在
        Dim ws As Worksheet
        On Error Resume Next
        Set ws = tB.Sheets(cell.Value)
        On Error GoTo 0
        ' 存在则执行复制,不存在则提示
        If Not ws Is Nothing Then
            ws.Copy
        Else
            MsgBox "无法找到工作表:" & cell.Value, vbExclamation
        End If
    Next cell
    
  • 简化冗余循环逻辑
    当前代码嵌套了三层循环,但ExportArray每次仅存储单个单元格值,最内层的For Each ShName In ExportArray完全多余,直接去掉可减少出错概率,优化后的核心循环如下:

    For Each Row In Attachments
        For Each cell In Row
            Set tB = ThisWorkbook
            If cell.Value = "" Then Continue For
            Dim ws As Worksheet
            On Error Resume Next
            Set ws = tB.Sheets(cell.Value)
            On Error GoTo 0
            If Not ws Is Nothing Then ws.Copy
        Next cell
    Next Row
    
  • 确认ThisWorkbook的指向
    tB = ThisWorkbook指代的是包含当前VBA代码的工作簿,如果你的目标工作表在其他打开的工作簿中,需要替换为正确的工作簿引用,比如Set tB = Workbooks("目标文件.xlsx")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:28:16