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

Error 91问题:DB表无数据时DataBodyRange.Copy报错的解决方法

Error 91规避方案(ListObject无数据场景)

问题原因

当DB工作表的ListObject(名为DB)没有数据时,tabledb.DataBodyRange会返回Nothing,此时直接调用.Copy方法就会触发Error 91(对象变量或With块变量未设置)。

规避方案

方案1:判断DataBodyRange是否存在

在执行复制操作前,先检查tabledb.DataBodyRange是否不为空,仅当有数据时才执行复制粘贴逻辑:

Sub PullDBData()
    Dim tabledb         As ListObject
    Dim tableisin       As ListObject
    Dim lr              As Long

    Set tabledb = Sheets("DB").ListObjects("DB")
    tabledb.QueryTable.Refresh BackgroundQuery:=False
    
    ' 新增:判断是否有数据行
    If Not tabledb.DataBodyRange Is Nothing Then
        tabledb.DataBodyRange.Copy
        lr = Sheets("Current").Cells(Rows.Count, 1).End(xlUp).Row + 1
        Sheets("Current").Range("A" & lr).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    End If
    
    tabledb.QueryTable.Refresh BackgroundQuery:=False

    Set tableisin = Sheets("Current").ListObjects("ISIN_2")
    tableisin.QueryTable.Refresh BackgroundQuery:=False
End Sub

方案2:通过ListRows数量判断

检查ListRows.Count是否大于0,以此确认是否存在数据:

Sub PullDBData()
    Dim tabledb         As ListObject
    Dim tableisin       As ListObject
    Dim lr              As Long

    Set tabledb = Sheets("DB").ListObjects("DB")
    tabledb.QueryTable.Refresh BackgroundQuery:=False
    
    ' 新增:判断数据行数量是否大于0
    If tabledb.ListRows.Count > 0 Then
        tabledb.DataBodyRange.Copy
        lr = Sheets("Current").Cells(Rows.Count, 1).End(xlUp).Row + 1
        Sheets("Current").Range("A" & lr).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    End If
    
    tabledb.QueryTable.Refresh BackgroundQuery:=False

    Set tableisin = Sheets("Current").ListObjects("ISIN_2")
    tableisin.QueryTable.Refresh BackgroundQuery:=False
End Sub

额外优化提示

  • 可在无数据时添加提示,比如MsgBox "DB工作表无数据可复制",方便快速知晓当前状态。
  • 代码中重复的tabledb.QueryTable.Refresh可合并为一次,避免重复刷新浪费资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:53:37