【问题标题】:Excel VBA - Using Ranges as Optional parameters for functions?Excel VBA - 使用范围作为函数的可选参数?
【发布时间】:2010-09-28 05:31:01
【问题描述】:

我想编写一个 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 循环包装在 If (R) Then...End If 语句中。

处理可选范围的方法是什么,如果范围存在,则通过 For Each 循环对其进行迭代?

【问题讨论】:

    标签: vba excel range


    【解决方案1】:

    试试这个

    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 调用该函数。

    【讨论】:

    • 对我来说Optional R As Variant 工作。在函数If IsMissing(R) Then Set R= Range("whatever") (Excel 2016) 中。
    【解决方案2】:

    解决方法:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多