Excel:连接列中的最后一个非空单元格

标签 excel vba

由于我的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

问题是函数永远不会结束,所以我的问题是:
  • 我的脚本有什么问题?
  • 我该怎么解决my problem ?
  • 最佳答案

    为了回答您的直接问题,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
    

    关于Excel:连接列中的最后一个非空单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609974/

    相关文章:

    excel - 从 Run 获取函数的返回值

    vba - Excel vba .Interior.ColorIndex 无法正常工作

    vba - 如何在循环中调整数组大小?

    excel - 计算满足多个条件的行数

    excel - 同步功能区下拉菜单以显示事件工作表

    javascript - JSON 键作为 JavaScript 中的 JSON 值

    loops - Excel宏: How to loop a chart making macro through a specific column every time the name in that column changes

    arrays - 在 Excel VBA 中的多个工作表中动态标注数组?

    vba - Excel VBA 用户窗体控件

    vba - "Reference must be to a macro sheet"错误