[翻译]  How to set a default value for an optional Range argument?

[CHINESE]  如何为可选的Range参数设置默认值?


I'm trying to write a function which would have a Range as an optional argument. Here's a minimal example of such function:

我正在尝试编写一个将Range作为可选参数的函数。这是这种功能的最小例子:

Function Example(s As String, Optional r As Range) As String
    Example = "Test"
End Function

This is ok and the VBA Module can be compiled. But I'm struggling to find out how to set a default value for this optional range argument, e.g. "B:B".

这没关系,可以编译VBA模块。但我很难找到如何为这个可选范围参数设置默认值,例如“B:B”。

Function Example(s As String, Optional r As Range **= Range("B:B")**) As String
    Example = "Test"
End Function

This does not compile. It throws the error "Constant expression required."

这不编译。它抛出错误“需要常量表达式”。

3 个解决方案

#1


5  

Check if the argument was passed inside the function and set it there if not.

检查参数是否在函数内部传递,如果没有则将其设置在那里。

Function Example(s As String, Optional r As Range) As String

    If r Is Nothing then Set r = Range("B:B")

    Example = "Test"

End Function

#2


3  

Scott's answer is probably the way to go, but if you really want to be able to put a literal default value in the function header, you could change the argument type to Variant and assign a default String to it, converting this string to a range in the body of the function if need be:

Scott的答案可能就是这样,但是如果你真的希望能够在函数头中放置一个文字默认值,你可以将参数类型更改为Variant并为其分配一个默认的String,将此字符串转换为一个范围在函数体中如果需要:

Function Example(Optional R As Variant = "A:B") As String
    If TypeName(R) = "String" Then Set R = Range(R)
    Example = R.Address
End Function

Tested like:

测试如下:

Sub test()
    Dim R As Range
    Set R = Range("A1:B1")

    Debug.Print Example()
    Debug.Print Example(R)
End Sub

Which prints:

哪个印刷品:

$A:$B
$A$1:$B$1

In some contexts the flexibility of being to pass either a range or a string to the function could be useful. For example, you could pass the name of a named range directly to the function and have it work as expected.

在某些情况下,将范围或字符串传递给函数的灵活性可能很有用。例如,您可以将命名范围的名称直接传递给函数,并使其按预期工作。

#3


3  

Thanks, Scott showed me the way. I googled this further and the proper way seems to be something like this:

谢谢,斯科特给我指路。我进一步搜索了这个,正确的方式似乎是这样的:

Function Example(s As String, Optional r As Range = Nothing) As String
    If IsMissing(r) Then
        r = Range("B:B")
    End If
    Example = "Test"
End Function

I can't fathom why you can define default values for pret

我无法理解为什么你可以为pret定义默认值


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号