vba Excel/VB 函数中的错误:“需要常量表达式”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5185595/
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-08 11:12:22  来源:igfitidea点击:

Error in Excel/VB function: "Constant expression required"

excelvba

提问by ANd

I'm new at VB and I'm having a hard time doing something that should be very simple.

我是 VB 的新手,我很难做一些应该非常简单的事情。

I'm trying to make an array of n+1 length and I keep getting "Constant expression required" when running the following code

我正在尝试创建一个长度为 n+1 的数组,并且在运行以下代码时不断收到“需要常量表达式”的消息

Function binomial(n As Integer, p As Double)
Dim probabilities(0 To n) As Double
End Function

I understand that the arguments used to build the array must be constants, but do I create one from the argument of the function?

我知道用于构建数组的参数必须是常量,但是我是否从函数的参数中创建了一个?

Thank you in advance

先感谢您

回答by RichardTheKiwi

You can't DIM against a variable size. ReDim it instead

您不能针对可变大小进行 DIM。ReDim 代替

For example

例如

Function binomial(n As Integer, p As Double)
Dim probabilities() As Double
ReDim probabilities(0 To n)
MsgBox LBound(probabilities)
MsgBox UBound(probabilities)
End Function

Sub test()
Call binomial(3, 2)
End Sub

Run the sub "test"

运行子“测试”