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
相关产品推荐
相关产品推荐

