在Excel VBA中的公式中自动定义的一组范围上运行公式

以下是我的工作表示例的图片:

工作表样本

我想C7中的单元格说“白色,蓝色,绿色”

而在C11中的单元格说“黑色,白色,绿色”使用完全相同的公式。

我想范围自动确定,所以我可以使用这个公式为每个父产品。

更多信息

我已经有了将brettdj的答案和超级用户的问题给定范围的单元组合在一起的代码,并且它工作的很好。

Function ConCat(ParamArray rng1()) As String Dim X Dim strOut As String Dim strDelim As String Dim rng As Range Dim lngRow As Long Dim lngCol As Long Dim lngCnt As Long strDelim = ", " For lngCnt = LBound(rng1) To UBound(rng1) If TypeOf rng1(lngCnt) Is Range Then If rng1(lngCnt).Cells.Count > 1 Then X = rng1(lngCnt).Value2 For lngRow = 1 To UBound(X, 1) For lngCol = 1 To UBound(X, 2) strOut = strOut & (strDelim & X(lngRow, lngCol)) Next Next Else strOut = strOut & (strDelim & rng2.Value) End If End If Next ConCat = Right$(strOut, Len(strOut) - Len(strDelim)) End Function 

现在我正在寻找一种方法来自动select'B'中的范围,从当前行-1开始,在列中search第一个空格+1 ,向下search当前行-1

在UDF中,您可以使用Application.Caller (或Application.ThisCell )获取对包含单元格的引用,然后您可以从那里移动…

 Function ConCat() As String Application.Volatile 'Need this since there are no input ' parameters to trigger recalculation Const DELIM As String = ", " Dim s As String Dim rngF As Range On Error GoTo haveError 'Where is the firmula being called from? Set rngF = Application.Caller 'Move to the correct column Set rngF = rngF.Offset(0,-1) 'use an offset 'Set rngF=rngF.EntireRow.Cells(1,"Y") 'use a fixed column 'Exit if not in a good starting location If rngF.Value <> "" Then Exit Function 'Move up until we're below the next space up Do While rngF.Offset(-1, 0) <> "" Set rngF = rngF.Offset(-1, 0) Loop 'Move down from there, adding to the string Do While rngF.Value <> "" s = s & IIf(s <> "", DELIM, "") & rngF.Value Set rngF = rngF.Offset(1, 0) Loop ConCat = s Exit Function haveError: 'If you use this formula when there's no space to go "up" ' or "left" then it will error on the Offset() call... ConCat = "Err!" 'or just return an empty string if you prefer End Function