Excel vba更改parameter passing给函数

说我有一个函数,需要两个Date参数。 然后我需要改变其中的一个(比如说,我需要改变它的月份)。 是唯一的方法来做它重新分配给variables,然后改变或可以通过参数名称引用它来改变?

 Function test(date1 As Date, date2 As Date, change As Boolean) If change=True Then date1 = DateSerial(year(date1), 10, day(date1)) 'would it change date1's month or not? End If test=date1 End Function 

通常认为最好的做法是不要改变投入,尽pipe没有任何东西阻止你这样做 – 这些论据就像程序中的variables一样被对待。 简而言之,简单的function,你可以摆脱它。 但是,如果你有一个更长,更复杂的function,你坚持永不改变input,你的代码变得更容易维护。

假设你从用户那里得到一个date,但你想回到最后一个声明date,这个date总是上个月的最后一天。 你可以像这样操纵参数

 Public Function LastStatementAmount(ByVal inputDate As Date) As Double Dim Return_ As Double inputDate = DateSerial(Year(inputDate), Month(inputDate), 0) 'do calculations here LastStatementAmount = Return_ End Function 

这是有效的。 但更好的方法是更改​​variables名称以反映您对该值所做的更改

 Public Function LastStatementAmount(ByVal inputDate As Date) As Double Dim Return_ As Double Dim stmtDate As Date stmtDate = DateSerial(Year(inputDate), Month(inputDate), 0) 'do calculations here LastStatementAmount = Return_ End Function 

如果这是一个更大的function,最好是看到stmtDate并知道你已经修改了inputdate。

如注释中所述,不改变input参数的另一个原因是,如果不指定传递机制,那么该参数默认情况下是ByRef,如果调用过程期望值没有改变,你可能会破坏代码。 你应该总是指定ByVal或ByRef,这样就清楚了你的代码的意图。

在代码中你可以使用Date1和Date2作为variables,所以你可以改变它们的值。 variablesDate1和Date2在函数语句中声明,所以它们的作用域纯粹是函数。 因此,担心改变input在UDF的angular度上是错误的 – date1和date2在其他任何地方都不存在。 如果你在另一个例程中使用这个,那么你确实可能冒这个风险,所以你可以用Value来声明它们

函数testing(ByVal Date1 As Date,ByVal Date2 As Date,更改为布尔值)