简体   繁体   English

Excel VBA - 使用范围作为函数的可选参数?

[英]Excel VBA - Using Ranges as Optional parameters for functions?

I'd like to write a VBA function that has a Range as an optional parameter. 我想写一个VBA函数,它有一个Range作为可选参数。 For instance something like: 例如:

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

I tried the function above, but I get a #VALUE! 我尝试了上面的功能,但我得到了一个#VALUE! error. 错误。 I also tried wrapping the For loop inside an If (R) Then...End If statement. 我还尝试在For(R)Then ... End If语句中包装For循环。

What would be the way to deal with an optional Range, where if the range exists, then it is iterated through via a For Each loop? 什么是处理可选范围的方法,如果范围存在,那么它是通过For Each循环迭代的?

Try this 试试这个

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

I've tested this okay in Excel 2007. You need to put it into a Module, not the Worksheet or Workbook code sections. 我已经在Excel 2007中测试了这个。你需要将它放入模块,而不是工作表或工作簿代码部分。 The function can then be called from VBA with or without a Range object, or as a worksheet function. 然后可以从带有或不带Range对象的VBA调用该函数,或者作为工作表函数调用该函数。

Workaround: 解决方法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM