[英]Excel VBA - Using Ranges as Optional parameters for functions?
我想写一个VBA函数,它有一个Range作为可选参数。 例如:
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! 错误。 我还尝试在For(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中测试了这个。你需要将它放入模块,而不是工作表或工作簿代码部分。 然后可以从带有或不带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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.