excel - 当我调用函数以使用从其他宏的工作表中获取的数据时,错误弹出。谁能解释为什么说 'object required'?

标签 excel vba object error-handling datastore

我想将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行,希望x2,以便循环更新第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/

相关文章:

python - 函数完成时对象是否从内存中删除? Python

excel - 循环问题 VBA - 粘贴在最后一行

python - 为什么 pandas dataframe 在从 excel 中读取列名后会引入额外的数字?

vba - 为什么返回 Range 的 Excel/VBA 用户定义的默认属性的行为与 Range 不同?

xml - 更改自定义 Excel 功能区下拉列表的大小

excel - 引用相对于 ActiveX 命令按钮 VBA 的单元格

javascript - 如果javascript将一个数据包含在数组中为真,如何使用 'if'?

java - 从静态方法中了解调用者对象或线程

excel - vba application.ontime返回函数值

python - 从 Python 调用现有的 DDE(彭博数据提供商)