我得到一个运行时错误1004如果我运行活跃注释掉线子。 它运行罚款,是的,但我需要增加阵列中的另一个循环读取更多的数据。 我宁愿使用范围(单元格选项。
Option Explicit
Dim myarray As Variant
'There are 6 numbers stored in a1 to a6 on sheet1
Sub read_as_entire_()
'This line fails if I use Cells...
'myarray = Worksheets("Sheet2").Range(Cells(1, 1), Cells(6, 1)).Value
'This line works fine
myarray = Worksheets("Sheet2").Range("a1:a6").Value
Sheet2.Range("b1:b6") = myarray
'Sheet2.Range(Cells(1, 2), Cells(6, 2)) = myarray
End Sub
有什么不同?
“细胞”是指一个范围的活性片(它不是“Sheet 2中”否则它会工作),则工作表(“Sheet 2中”)。范围仅接受“Sheet2的”工作表的范围,因此它产生一个错误。 你可以解决这个问题:
myarray = Worksheets("Sheet2").Range(Worksheets("Sheet2").Cells(1, 1), Worksheets("Sheet2").Cells(6, 1)).Value
或更短
with Worksheets("Sheet2")
myarray = .Range(.Cells(1, 1), .Cells(6, 1)).Value
end with
我更喜欢使用
myarray = Worksheets("Sheet2").Cells(1, 1).Resize(6,1)
我怀疑,这是不是指到Sheet2,当你引用单元格中的注释部分。 它所指的可能是活动工作表来代替。
为了检验这一尝试修改线以下:
With Worksheets("Sheet2")
myarray = .Range(.Cells(1, 1), .Cells(6, 1)).Value
End With
我使用与构建体,这意味着,当我使用公式它指的是在最近的与语句块开头引用的对象的点(“”)。