将行组合成一个单元格

时间:2015-02-27 19:14:10

标签: excel

我想知道是否有一种简单的方法将每个Hl7消息的所有行组合成一个单元格,我有一个巨大的HL7消息列表,每条消息以尖括号结束">" 。可以使用公式或VBA代码完成吗?

这是我想要实现的目标

Original

Transformed

3 个答案:

答案 0 :(得分:0)

编辑: 我想我最初误解了目标。请尝试以下并报告。

Sub Join()
Dim X as Variant
Dim C as range
Dim I as Integer
Dim str as string
For Each C in Workbooks("TEST").Sheets("Sheet1").Range("a1").currentregion
   str = str & C 'Changed to make sure they are written in the correct order
Next C
X = Split(str, ">")
For I = 0 to ubound(x)
Workbooks("TEST").Sheets("Sheet1").Cells(I+1,2) = x(I) & ">"
Next I
End Sub

答案 1 :(得分:0)

如果你想要从左边的(over?)简化输入数据示例中突出显示输出,那么在选择all,Copy,Paste Special,Values和FilterC选择之前,所示的两个公式将实现此目的并删除显示FALSE的行:

SO28772576 example

答案 2 :(得分:0)

这是另一种解决方案。它并不优雅,但格式与您在上面的图像中显示的完全相同,每行末尾都有一个回车符,“>”删除,以及消息之间的空单元格。我将结果放在B列中,这样我就能看出它是否正常工作。你当然可以根据自己的需要定制它。

Sub DoMessages()

    Dim HL7Message As String
    Dim newHL7Message As String
    Dim i As Integer: i = 2
    Dim j As Integer: j = 1
    Dim lastRow As Integer

    lastRow = Sheets(1).Cells(1000, "A").End(xlUp).Row 'I used "1000" for the sake of this test code. Change as required.

    HL7Message = Cells(1, 1).Value

    For i = 1 To lastRow
        newHL7Message = Cells(i, 1).Value
        If Not newHL7Message = ">" Then
            If HL7Message = "" Then 'This 'If-Then-Else' keeps from there being an extra CR at the beginning of each cell
                HL7Message = newHL7Message
            Else
                HL7Message = HL7Message & vbCrLf & newHL7Message
            End If
        Else
            Sheets(1).Cells(j, 2) = HL7Message
            HL7Message = ""
            j = j + 2
        End If
    Next

End Sub