使用换行将两列逐行连接到单个单元格中

时间:2018-02-10 15:09:27

标签: excel-vba concatenation user-defined-functions vba excel

我正在尝试发展一个名为concall(Range1,Range2)的用户定义函数,它将让我首先连接A1和B1中的文本,然后添加新行,然后根据范围连接A2和B2等等。
假设,如果从A1到A4的数据是
一个

ç
d

从C1到C4是
阿尔法
贝塔
伽玛
德尔塔

如果我在任何单元格中输入concall(A1:A4,C1:C4),它应该在该单元格中显示以下内容

A - 阿尔法 B - Beta
C - Gamma
D - Delta

示例图片文件为Sample Image

目前,我手动连接两列,然后使用以下代码将多行数据连接到一个单元格。

Public Function rconc(data_range As Range)
Dim Cll As Range
For Each Cll In data_range
If Cll <> "" Then
rconc = rconc & vbCrLf & Cll
End If
Next Cll
If Len(rconc) > 0 Then rconc = Mid(rconc, 2)
End Function

1 个答案:

答案 0 :(得分:3)

怎么样:

Public Function KonKat(r1 As Range, r2 As Range) As String
    Dim arr, brr, v As Range
    ReDim arr(1 To r1.Count)
    ReDim brr(1 To r2.Count)

    KonKat = ""
    i = 1
    For Each v In r1
        arr(i) = v.Value
        i = i + 1
    Next v
    i = 1
    For Each v In r2
        brr(i) = v.Value
        i = i + 1
    Next v

    KonKat = ""
    For i = 1 To r1.Count
        If KonKat = "" Then
            KonKat = arr(i) & "-" & brr(i)
        Else
            KonKat = KonKat & vbCrLf & arr(i) & "-" & brr(i)
        End If
    Next i

End Function

enter image description here

修改#1:

要避免其中任何一个成员为空的记录,请将最后一个For循环替换为:

For i = 1 To r1.Count
        If arr(i) <> "" And brr(i) <> "" Then
            If KonKat = "" Then
                KonKat = arr(i) & "-" & brr(i)
            Else
                KonKat = KonKat & vbCrLf & arr(i) & "-" & brr(i)
            End If
        End If
 Next i