数组参数必须是 ByRef [英] Array argument must be ByRef
问题描述
我在这里做错了什么?
Sub Main()
Dim patients() As String
' Some code to populate the patients array, works fine
CalculateScores (patients) ' Array argument must be ByRef compile error
End Sub
Sub CalculateScores(patients As String)
End Sub
如果我将患者更改为 Main 中的变体数组,并且CalculateScores 的参数可以正常工作,但我看不到无法传递字符串的逻辑.默认情况下它是 ByRef 所以我知道我错过了一些东西.
If I change patients to a variant array in Main and the parameters of CalculateScores it works fine but I can't see the logic of not being able to pass a string. By default it is ByRef so I know I'm missing something.
我当然可以使用变体,但感觉很笨拙.
I can use a variant sure, but it feels hacky.
推荐答案
当你这样做时:
DoSomething (expression)
您强制将 expression
评估为 作为值,并传递 ByVal
,无论参数是否明确说明它通过了 ByRef.虽然大多数时候这或多或少没有影响,但当您尝试传递数组或对象引用时,它会在后端咬你.
You're forcing expression
to be evaluated as a value, and passed ByVal
, regardless of whether the parameter explicitly says it's passed ByRef. While that has more or less no impact most of the time, it bites you in the rear end when you try to pass an array or an object reference.
去掉括号.
DoSomething expression
<小时>
现在,您的代码还有其他问题:您将字符串数组传递到 String
参数中;那不行.将参数设为数组或 Variant
,为了清楚起见,我建议将参数明确标记为 ByRef
.
Now, there are other problems with your code: You're passing an array of strings into a String
parameter; that can't work. Make the parameter an array or a Variant
, and I'd suggest marking the parameter explicitly as ByRef
, for clarity.
这篇关于数组参数必须是 ByRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!