VBA如何在函数中使用可选参数

时间:2022-03-31 11:00:51

how do i use optional arguments in Visual Basic for aplications

我如何在Visual Basic中使用可选参数进行应用程序

the following code receives a range of strings and concatonates them with a seperator.

以下代码接收一系列字符串并使用分隔符将它们连接起来。

Function concat(range, sep)
mystring = ""

For Each item In range
    mystring = mystring & sep & item
Next

mystring = Right(mystring, Len(mystring) - Len(sep)) 'removes preceding separator
concat = mystring
End Function

i want sep to be an optional argument so i can call concat(range) instead of concat(range;"")

我希望sep是一个可选参数,所以我可以调用concat(范围)而不是concat(范围;“”)

example in python:

python中的示例:

def concat(range, sep="")
    mystring = ""
    for i in range:
        mystring += sep + i
    mystring = mystring[len(sep)::]
    return mystring

1 个解决方案

#1


3  

You will want to declare the types.

您需要声明类型。

Use the keyword Optional

使用关键字Optional

Function concat(rng As range, Optional sep As String = "")
Dim mystring As String
Dim itm As range
mystring = ""

For Each itm In rng
    mystring = mystring & sep & itm
Next

mystring = Right(mystring, Len(mystring) - Len(sep)) 'removes preceding separator
concat = mystring
End Function

#1


3  

You will want to declare the types.

您需要声明类型。

Use the keyword Optional

使用关键字Optional

Function concat(rng As range, Optional sep As String = "")
Dim mystring As String
Dim itm As range
mystring = ""

For Each itm In rng
    mystring = mystring & sep & itm
Next

mystring = Right(mystring, Len(mystring) - Len(sep)) 'removes preceding separator
concat = mystring
End Function