Excel VBA-将动态范围传递给函数

时间:2018-07-10 19:50:13

标签: excel-vba

我在Excel VBA中创建了一个函数:

Function codeList(Criteria As String, LookupRange As Range, ValueRange As Range, delimiter As String)

当我像这样将硬编码范围传递给它时,效果很好:

ActiveCell.FormulaR1C1 = "=codelist(RC[2],R2C4:R84C4,R2C3:R84C3,"","")"

我希望行是动态的,所以我不想说C2:C84或D2:D84,而是让C84 / D84根据具有数据的列数而变化。

当我调用函数时,我试图计算最后一行并连接范围以使它们动态化,但是出现编译语法错误:

Dim lastRow As Long
lastRow = Range("C" & Rows.Count).End(xlUp).Row
ActiveCell.FormulaR1C1 = "=codelist(RC[2],"R2C4:R" & lastrow &"C4", "R2C3:R" & lastrow & "C3"),"","")"

关于如何进行这项工作的任何建议?

2 个答案:

答案 0 :(得分:0)

要在字符串中包含双引号时,必须使用两个双引号将其转义。

ActiveCell.FormulaR1C1 = "=codelist(RC[2],R2C4:R" & lastRow & "C4, R2C3:R" & lastRow & "C3,"""")"

末尾的四个双引号将转换为两个双引号(您要查找的空字符串)。

这种方式更长,但是我倾向于在公式中使用偏移量。我发现比尝试确定字符串的开始和结束位置更容易阅读

Const DBLQTE As String = """"""

ActiveCell.FormulaR1C1 = "=codelist(RC[2]," & _
    Range("D2").Resize(lastRow - 1).Address(, , xlR1C1) & _
    "," & _
    Range("C2").Resize(lastRow - 1).Address(, , xlR1C1) & _
    "," & _
    DBLQTE & _
    ")"

更新

用于逗号分隔符

ActiveCell.FormulaR1C1 = "=codelist(RC[2],R2C4:R" & lastRow & "C4, R2C3:R" & lastRow & "C3,"","")"

Const COMMA As String = ""","""
ActiveCell.FormulaR1C1 = "=codelist(RC[2]," & _
    Range("D2").Resize(lastRow - 1).Address(, , xlR1C1) & _
    "," & _
    Range("C2").Resize(lastRow - 1).Address(, , xlR1C1) & _
    "," & _
    COMMA & _
    ")"

答案 1 :(得分:0)

限定父级工作表并根据列的填充限制调整大小。调整每个需要相同大小的关联范围的大小。

Function codeList(Criteria As String, LookupRange As Range, ValueRange As Range, delimiter As String)

    with LookupRange.parent
        set LookupRange = .range(LookupRange.cells(1), .cells(.rows.count, LookupRange.cells(LookupRange.cells.count).column).end(xlup))
        set ValueRange = ValueRange.cells(1).resize(LookupRange.rows.count, LookupRange.columns.count)
    end with

    'all the rest of the code

end function

切勿在工作表的UDF中使用ActiveSheet或ActiveCell。公式所在的原始单元格为Application.Caller