Excel VBA – 使用范围作为可选参数的function?

我想编写一个范围作为一个可选参数的VBA函数。 比如像这样的东西:

Public Function testfunc(S As String, Optional R As Range) As String testfunc = S For Each cell In R testfunc = testfunc + cell Next cell End Function 

我试过上面的函数,但是我得到了一个#VALUE! 错误。 我也尝试在If(R)Then … End If语句中包装For循环。

如何处理一个可选的范围,如果范围存在,那么它将通过For Each循环来迭代?

尝试这个

 Public Function testfunc(S As String, Optional R As Range = Nothing) As String testfunc = S if not R is nothing then For Each cell In R testfunc = testfunc & cell Next cell end if End Function 

我已经在Excel 2007中testing了这一点。您需要将其放入模块,而不是工作表或工作簿代码部分。 然后可以使用或不使用Range对象或作为工作表函数从VBA调用该函数。

解决方法:

 Public Function testfunc(S As String, Optional R As String = vbNullString) As String testfunc = S If R <> vbNullString Then For Each cell In Range(R) ' & for concatenation not + ' testfunc = testfunc & cell Next cell End If End Function Sub test() MsgBox testfunc("", "A1:A5"), vbOKOnly, "Results" MsgBox testfunc(""), vbOKOnly, "Results" End Sub