[英]Run a formula on a set of ranges that are automatically defined within the formula in Excel VBA
這是我的工作表示例的圖片:
我希望C7中的單元格說“白色,藍色,綠色”
C11中的單元格使用完全相同的公式說“黑,白,綠”。
我希望范圍是自動確定的,因此我可以對每個母產品使用此公式。
更多信息
我已經有代碼來組合從brettdj的答案到 Superuser的問題的給定范圍內的單元格,並且效果很好。
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
現在,我正在尋找一種方法,該方法可以通過從當前行-1開始 ,在該列中搜索第一個空格+1 ,向下到當前行-1來自動選擇'B'中的范圍。
在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.