gpt4 book ai didi

vba - 将范围对象传递给 excel-vba 中的函数——收到 "Object Required"错误

转载 作者:行者123 更新时间:2023-12-01 05:47:02 24 4
gpt4 key购买 nike

我正在尝试构建一个函数,它将接受一个输入单元格(例如“B5”)并返回一个引用表格的范围对象(提供的单元格是右上角的条目)

Sub Macro1()
Dim testCell As Range

testCell = Worksheets("HMA").Range("B5")
ReturnTable testCell

End Sub

Function ReturnTable(cell As Range)
firstcell = cell
lastrow = firstcell.End(x1Down)
Table = Range(firstcell, lastrow + 5).Value
End Function

我在这里遇到了很多问题,我觉得我缺少一些简单的东西。我得到的错误是 lastRow 行的“Object Required”。

在 Debug模式下查看它,我看到 testCell 被分配了范围对象的值(我假设这是默认值)。我在这里错过了什么?

我的方法合理吗?我是否应该考虑以不同的方式解决这个问题?

最佳答案

End 返回一个 Range 对象,因此,lastrow 必须是一个范围变量。

Function ReturnTable(firstcell as Range) as Range 'add this as range to tell the result of the function is a range
dim LastCell as Range
Set LastCell = firstcell.END(xldown)
Set ReturnTable = Range(firstcell, lastcell) 'must use the same name of the function
End Function

如果你想在 lastcell 下面有 5 个单元格,使用 LastCell.Offset(5,0)

在 Macro1 中,您可能会想要类似的东西

Set SomeVar = ReturnTable(testcell)

关于vba - 将范围对象传递给 excel-vba 中的函数——收到 "Object Required"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com