由于我的previous post已关闭,但问题仍然存在,我会在此重述一下。我想出了以下内容:
Function JoinLastInColIfEmpty(range_ As Range, delim_ As String)
Dim cell As Range, result As String, current As String
For Each cell In range_
current = LastNonEmptyInCol(cell)
If current <> "" Then
result = result & current & delim_
End If
Next
If Not IsEmpty(result) Then
result = Left(result, Len(result) - Len(delim_))
End If
JoinLastInColIfEmpty = result
End Function
Function LastNonEmptyInCol(cell_ As Range)
Dim tmp As Range
tmp = cell_ '<< The problem occurs here
Do Until Not IsEmpty(tmp) Or tmp.Row = 1
tmp = tmp.Offset(-1, 0)
Loop
LastNonEmptyInCol = tmp.Value
End Function
问题是该功能永远不会结束,所以我的问题是:
答案 0 :(得分:2)
要回答您的直接问题,LastNonEmptyInCol
Function LastNonEmptyInCol(cell_ As Range)
On Error Resume Next
Dim tmp As Range
Set tmp = cell_ '<< The problem occurs here ' <<<<< use Set
Do Until Not IsEmpty(tmp) Or tmp.Row = 1 ' <<<<< use tmp not cell_
Set tmp = tmp.Offset(-1, 0) ' <<<<< use Set
Loop
LastNonEmptyInCol = tmp.Value
End Function
那就是说,我认为这是一个非常低效的解决方案,并没有完全解决你陈述的问题
结果将是
A | B | C | D | Concat
-----+-----+-----+-----+---------
1 | 2 | X | 5 | 12X5
| | f | 3 | 12f3
| 5 | R | 12 | 15R12
Z | 3 | T | | Z3T12
| G | | | ZGT12
这是另一个可能更好的版本
Function MyJoinLastInColIfEmpty(range_ As Range, delim_ As String)
Dim vData As Variant
Dim cl As Range
Dim i As Long
Dim result As Variant
vData = range_
For i = 1 To UBound(vData, 2)
If vData(1, i) = "" Then
Set cl = range_.Cells(1, i).End(xlUp)
If cl <> "" Then
vData(1, i) = cl.Value
End If
Else
Exit For
End If
Next
For i = 1 To UBound(vData, 2)
result = result & vData(1, i) & delim_
Next
MyJoinLastInColIfEmpty = Left(result, Len(result) - Len(delim_))
End Function
答案 1 :(得分:1)
我并没有真正尝试理解整个事情,但由于tmp是一个(范围)对象,你必须使用
Set tmp = ....
答案 2 :(得分:0)
使用帮助行/列可以使用公式实现:
- 在输入的单元格F1
数组中放置(Ctrl+Shift+Enter
)然后滚动到您拥有的多个单元格:
{=INDEX(A$1:A1,MAX(IF(ISBLANK(A$1:A1),0,ROW(A$1:A1))))}
- 放在单元格K1
中,指的是F1
中的第一个单元格,此处不需要数组。
=IF(ISBLANK(A1),IF(SUM(NOT(ISBLANK(INDEX($A1:A1,0)))+0)>0,"",F1),F1)
- 放置在任何你想要的结果。 MCONCAT
是UDF function found in a free Add-in written in C++,CONCATENATE
是Excel的内置公式。
=MConCat(K1:N1)
或=CONCATENATE(K1,L1,M1,N1)
我个人的偏好是VBA的方式。我敢肯定比我聪明的人能想出更好的公式。