编写VBA过程后cc与ccc对象始终为Nothing,求原因分析
分析变量cc和ccc始终为Nothing的原因
以下是几种最可能的情况:
1. 列表对象或列名称不匹配
- 确认Sheet20中确实存在名为
Table_ProcessIndexes_All和Table_ProcessIndexes_Selection的ListObject表格,名称要完全一致(包括大小写、空格、特殊字符)。 - 检查列名称:
"Process Indexes all"和"Process Indexes Selection"必须和对应表格的列标题完全一致,哪怕多一个空格或者大小写不同,都会导致ListColumns返回Nothing,进而后续的DataBodyRange也是Nothing。
2. 表格无数据行(仅存在表头)
ListObject的DataBodyRange仅在表格有至少一行数据时才会返回有效Range对象,如果表格只有表头、没有任何数据行,DataBodyRange就会是Nothing,自然cc和ccc也会被设为Nothing。
3. 代码中cc的访问方式冗余且易出错
你给cc赋值的代码是:
Set cc = Sheet20.ListObjects("Table_ProcessIndexes_All").ListColumns( _ "Process Indexes all").DataBodyRange.Cells
如果DataBodyRange已经是Nothing,再访问.Cells只会保留Nothing状态。建议先单独获取DataBodyRange并判断是否存在:
Dim sourceCol As ListColumn Set sourceCol = Sheet20.ListObjects("Table_ProcessIndexes_All").ListColumns("Process Indexes all") If Not sourceCol Is Nothing Then If Not sourceCol.DataBodyRange Is Nothing Then Set cc = sourceCol.DataBodyRange.Cells End If End If
额外代码问题提示
- 当你执行
ccc.Delete后,ccc会变成Nothing,后续循环里的ccc.Cells(i, 0).Value = i.Text会直接报错,因为不能访问Nothing对象的属性。 - 字典的Keys是字符串类型,
i.Text写法错误,直接用i即可,因为i本身就是字典里存的文本值。
内容的提问来源于stack exchange,提问作者71GA
相关产品推荐
相关产品推荐

