更改数组 VBA 中元素的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17438141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:01:58  来源:igfitidea点击:

Change value of an element in an array VBA

excelfunctionvbarange

提问by user235319

The following user defined VBA function does not give a specific error yet does not return a value. I have no idea why. Can anyone suggest how to amend this code so that it works? Thanks so much!

以下用户定义的 VBA 函数未给出特定错误但未返回值。我不知道为什么。谁能建议如何修改此代码以使其正常工作?非常感谢!

Public Function mytest(myrange As Range)

myrange(1).Value = myrange(1).Value * 44

mytest = myrange(1).Value

End Function

I would call this function in a cell as follows for example;

例如,我会在单元格中调用此函数,如下所示;

=mytest(A1)

Cell A1 would contain a value, say 10. I would hope the function returns value 440.

单元格 A1 将包含一个值,例如 10。我希望该函数返回值 440。

回答by Andy G

A user-defined function that you call/use in a worksheet cannot (added: without external help, such as complex win-api calls) change the application-environment. That is, you cannot use an UDF in a cell that would change any other cell, either its value or formatting.

您在工作表中调用/使用的用户定义函数不能(添加:没有外部帮助,例如复杂的 win-api 调用)更改应用程序环境。也就是说,您不能在单元格中使用 UDF 来更改任何其他单元格,无论是其值还是格式。

Put it this way, there are no Excel functions that ever change another cell are there?

这么说吧,有没有可以改变另一个单元格的 Excel 函数呢?

If you want to change the value of a cell then you need to create and run a sub-procedure.

如果要更改单元格的值,则需要创建并运行过程。

Added: A function that you want to use in a worksheet should behave like any Excel function; it performs calculations and returns a value. For example:

添加:您想在工作表中使用的函数应该像任何 Excel 函数一样;它执行计算并返回一个值。例如:

Public Function MyTest(myRange As Range) As Double
    'return a value by assigning it to the function name:
    MyTest = myRange(1).Value * 44
End Function