如何使用 VBA 从 Excel 中的公式获取单元格值?
我在工作表中的一系列单元格中有一个公式,其计算结果为数值。 如何从传递给函数的范围中获取 VBA 中的数值?
假设工作表中 A 列的前 10 行包含 rand(),我将其作为参数传递给我的函数...
public Function X(data as Range) as double
for c in data.Cells
c.Value 'This is always Empty
c.Value2 'This is always Empty
c.Formula 'This contains RAND()
next
end Function
我从单元格调用该函数...
=X(a1:a10)
我如何获取单元格值,例如0.62933645?
Excel 2003、VB6
I have a formula in a range of cells in a worksheet which evaluate to numerical values. How do I get the numerical values in VBA from a range passed into a function?
Let's say the first 10 rows of column A in a worksheet contain rand() and I am passing that as an argument to my function...
public Function X(data as Range) as double
for c in data.Cells
c.Value 'This is always Empty
c.Value2 'This is always Empty
c.Formula 'This contains RAND()
next
end Function
I call the function from a cell...
=X(a1:a10)
How do I get at the cell value, e.g. 0.62933645?
Excel 2003, VB6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 VBA (Excel 2003) 运行时,以下代码适用于我:
a 和 b 相同且等于我传入的内容(这是其中包含 Rand() 的单元格范围)。 我不确定这里还发生了什么。
啊哈! 你需要设置X,不是吗? 我不确定您到底希望这个函数做什么,但您需要将 X (函数的名称)设置为您想要返回的值。 添加这一行:
The following code works for me when running from VBA (Excel 2003):
a and b are the same and equal what I'm passing in (which is a range of cells with Rand() in them). I'm not sure what else is going on here.
Aha! You need to set X, no? I'm not sure what exactly you expect this function to do, but you need to set X (the name of the function) to the value you want returned. Add this line:
我无法使用您发布的布局复制问题。 我注意到您发布的代码中存在一些语法错误(即:“for”应该是“foreach”)。 但是,当我将 =RAND() 放入 A1:A10 和 =X(A1:A10) 中时,我得到了一个很好的回报:
但是,只是为了进一步扩展您遇到的其他一些问题。 您可以像这样计算结果的公式:
但一般来说您不会想要,因为这基本上是计算相同的值两次。
I can't replicate a problem using the layout you posted. I noticed a few syntax errors in your posted code (ie: "for" should be "for each"). But when I put =RAND() in A1:A10 and =X(A1:A10) I got a return just fine with this:
However, just to a expand a little more on a few of the other questions you brushed up against. You can evaluate a formula for a result like so:
But generally speaking you won't want to, as this is basically calculating the same value twice.
确保在请求该值之前进行计算。
为了加速宏,通常会执行如下所示的操作。
在这种状态下,您必须在值可用之前强制计算。
Make sure you do a calculate before requesting the value.
To Speed up macros something like the following is often preformed..
in this state you must force calculation before the value will be available.