如何调用只传递一个可选参数的函数?

时间:2014-02-17 09:27:04

标签: vba

如果我的功能看起来像

function(optional byval string1 as String,optional byval string2 as String,optional byval string3 as String )

我只想通过在单元格中输入string3来提供"=function(string3)"来调用该功能,我该怎么做?

1 个答案:

答案 0 :(得分:1)

可能有两种方式之一......

  1. 调用例程并通过“跳过”不可用的参数来识别正在使用的可选参数:
  2. Function MyFunc(optional a as integer, _
                    optional b as integer, _
                    optional c as integer) as double
        MyFunc = c * 3.14159
    End Function
    
    =MyFunc(,,12)   <== called as UDF on worksheet or in VBA module
    
    1. 使用参数列表对函数进行编码:
    2. Function MyFunc(args() As Variant) As Double
          Dim numberOfArgs As Integer
          Dim arg As Variant
          Dim i As Integer
          Dim answer As Double
          numberOfArgs = UBound(args)
          i = 1
          For Each arg In args
              Debug.Print "arg(" & i & ") = " & arg
              answer = Int(arg) * 3.14159
              i = i + 1
          Next arg
          MyFunc = answer
      End Function
      
      Sub test1()
          Dim parms() As Variant
          ReDim parms(1 To 3)
          'parms(1) = ??
          'parms(2) = ??
          parms(3) = 21
          Debug.Print MyFunc(parms)
      End Sub