我想将Excel工作表中的数据存储到数组中,然后在不同的宏中使用它们。我编写了以下函数来存储数据,然后在不同的宏中调用它,但 pop 错误并显示“Object required”。请帮我。
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
关于excel - 当我调用函数以使用从其他宏的工作表中获取的数据时,错误弹出。谁能解释为什么说 'object required'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47958941/