我想将excel表中的数据存储到数组中,然后在不同的宏中使用它们。我编写了以下函数来存储数据,然后我在不同的宏中调用它,但弹出一个错误并说“需要对象”。请帮我。
Public Function data()
Dim i, j, t1, t2 As Integer
Dim x As Range
Dim dt() As Date
Dim price(), bch() As Single
Dim chp(), chb() As Integer
Sheets("Data").Select
Range("B8").Select
Set x = ActiveSheet.UsedRange.Range("B8").End(xlDown).Rows.Count 'getting the range
For i = 1 To x 'stores data into the array
Cells(i + 8, 1).Value = dt(i - 1)
Cells(i + 8, 2).Value = price(i - 1)
Cells(i + 8, 3).Value = bch(i - 1)
Cells(i + 8, 4).Value = chp(i - 1)
Cells(i + 8, 5).Value = chb(i - 1)
Next
End Function
你不能将Range
设置为数字。所以声明
Set x = ActiveSheet.UsedRange.Range("B8").End(xlDown).Rows.Count
不行。
ActiveSheet.UsedRange.Range("B8").End(xlDown)
将指单个单元格,因此其Rows.Count
将始终返回数字1。
所以你得到一个错误,因为你试图将x
(一个Range
)设置为1
(一个Long
)。
根据你在x
循环中使用For i = 1 to x
,以及你在i + 8
循环中的使用来判断,你似乎试图找到在第8行下面使用了多少行(所以,如果最后使用的行是第10行,你似乎希望x
成为2
,以便循环更新第9行和第10行,所以你真的想要使用:
Dim x As Long
x = ActiveSheet.Range("B8").End(xlDown).Row - 8
仅供参考,也请注意
Dim i, j, t1, t2 As Integer
相当于
Dim i As Variant, j As Variant, t1 As Variant, t2 As Integer
不要
Dim i As Integer, j As Integer, t1 As Integer, t2 As Integer