无法将动态范围作为参数传递

时间:2016-05-08 07:23:06

标签: vb.net excel vba scripting

当我尝试使用下面的函数时,我无法将动态范围作为参数传递

Function ConcatinateAllCellValuesInRange(sourceRange As Excel.Range) As String
    Dim finalValue As String

    Dim cell As Excel.Range

    For Each cell In sourceRange.Cells
        finalValue = finalValue + CStr(cell.Value)
    Next cell

    ConcatinateAllCellValuesInRange = finalValue
End Function

Sub MyMacro()
    MsgBox ConcatinateAllCellValuesInRange([A1:C3])
End Sub

我无法使用

Sub MyMacro()
    Dim rng as range
    Rng=Range(Range("A2"),Range("A2").End(xlDown).Row))
    MsgBox ConcatinateAllCellValuesInRange([Rng])
End Sub

1 个答案:

答案 0 :(得分:0)

你的语法错了。

要定义对象,您需要使用Set关键字; .Row函数返回Long而不是Range对象,因此您需要将其删除;你只需在你的函数中传递rng变量。

Function ConcatinateAllCellValuesInRange(sourceRange As Range) As String
    Dim finalValue As String

    Dim cell As Excel.Range

    For Each cell In sourceRange.Cells
        finalValue = finalValue &  CStr(cell.Value)
    Next cell

    ConcatinateAllCellValuesInRange = finalValue
End Function

Sub MyMacro()
    Dim rng As Range
    Set rng = Range(Range("A2"), Range("A2").End(xlDown))
    MsgBox ConcatinateAllCellValuesInRange(rng)
End Sub