联合function不适用于单细胞范围vba

在这段代码中,我试图使用联合函数按单元格构build一个范围单元格。

Function getColumnFromRowIndices(ByRef ws As Worksheet, columnHeader As String, rowIndices() As Long, ByRef headerCells_byHeader As Dictionary) As range Dim gCFRI As range 'function alias Dim cL As String: cL = getColumnLetterOfCell(headerCells_byHeader(columnHeader)) If Not IsEmpty(rowIndices) Then Dim rI As Variant: For Each rI In rowIndices If gCFRI Is Nothing Then Set gCFRI = ws.range(cL & CLng(rI)) _ Else Set gCFRI = Union(gCFRI, ws.range(cL & CLng(rI))) Next rI End If Set getColumnFromRowIndices = gCFRI End function 

我遇到的问题是工会没有build立起来。 当我在监视窗口中观看ws.range(cL&CLng(rI))时,它会按照预期列出我要添加的新单元。 但是在这种情况下,联合会在每次被调用时恢复到arg1。

我必须做什么来解决这个问题?

移动:

 Dim gCFRI As range 

UDF之外的UDF所在的模块的顶部。 这将允许范围“记住”以前的值,并根据需要“积聚”。