Excel VBA使用Cells变量定义Range触发运行时错误1004如何解决?
报错根因
问题核心是Cells对象未显式指定所属工作表,默认引用当前激活的工作表,和前面Range所属的Sheets(export)不一致,当激活表不是目标表时,跨表构造Range就会触发1004错误。
你用列字母拼接地址的写法可以正常运行,是因为直接传入的地址字符串会由Sheets(export)的Range对象自行解析,不存在父表不匹配的问题。
解决方案
- 显式为所有
Cells指定和Range相同的父工作表,推荐用With块简化写法,避免重复写工作表引用 - 如果是要将单元格值存入数组,不需要加
Set关键字,只有赋值Range对象时才需要Set - 单行/单列区域读入的数组默认为二维结构,取值时需要同时指定行、列索引,不能仅用列索引
修正后代码示例
Dim export As String: export = "Table1" Dim headline As Integer: headline = 7 Dim ic_from_col As Integer: ic_from_col = 30 Dim ic_to_col As Integer: ic_to_col = 40 Dim ICNames As Variant Dim key As Integer: key = 1 ' 统一绑定目标工作表 With Sheets(export) ' 直接读入单元格值到数组,不需要Set ICNames = .Range(.Cells(headline, ic_from_col), .Cells(headline, ic_to_col)).Value End With ' 单行区域的行索引固定为1 MsgBox ICNames(1, key)
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

