如何在两个单元格的值之间换行

时间:2019-07-20 01:32:28

标签: excel vba

我正在尝试根据两个单元格的值来完成换行公式。更具体地说,CONTINGENCYEND。因此,示例如下所示: `

CONTINGENCY'XXX'

断开总线1

断开总线2

断开总线3

断开4总线的连接

END
-------------------`


我想要的输出就是这样 CONTINGENCY 'XXX' DISCONNECT BUS 1 DISCONNECT BUS 2 DISCONNECT BUS 3 DISCONNECT BUS 4 END

将其合并到contingencyend之间的一个单元格中。

SAMPLE OUTPUT

我还必须为10000行代码执行此操作。我应该放置一个标识符或诸如contingency的唯一ID号之类的东西吗?打开任何建议或解决方案。

因此,我使用自动换行并使用CHAR(10)进行换行,但无法找出用于特定单元格值或标识符的代码。

=C2&Q&C3&Q&C4&Q&C5&Q&C6&Q&C7,其中Q=CHAR(10)

2 个答案:

答案 0 :(得分:0)

使用示例中的代码并对其进行操作以供使用:

赞:

With Worksheets(1).Range("c1:c10000") 'Change the worksheet & Range
     Set c = .Find("Contingency", lookin:=xlValues) 'change the lookup text 
     If Not c Is Nothing Then
        firstAddress = c.Address
        Do
             c.Value = 5 ' Put your concatenate code here instead of this line
            Set c = .FindNext(c)
        If c is Nothing Then
            GoTo DoneFinding
        End If
        Loop While c.Address <> firstAddress
      End If
      DoneFinding:
End With

来自:Range.FindNext

答案 1 :(得分:0)

以下代码循环遍历所有行,用“ CONTINGENCY”标识行,并在此处连接非空单元格值。

Private Sub ConcatCells()
    Dim ws As Worksheet
    Dim currentRow As Long, concatRow As Long, lastRow As Long

    Set ws = ActiveWorkbook.Sheets("Whatever")

    With ws
        lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
        For currentRow = 1 To lastRow

            If Left(.Cells(currentRow, "C").Value, 11) = "CONTINGENCY" Then
                concatRow = currentRow
                .Cells(concatRow, "D").Value = .Cells(currentRow, "C").Value

            ElseIf Left(.Cells(currentRow, "C").Value, 3) = "END" Then
                .Cells(concatRow, "D").Value = _
                    .Cells(concatRow, "D").Value & vbLf & _
                    .Cells(currentRow, "C").Value

            ElseIf .Cells(currentRow, "C").Value <> "" Then
                .Cells(concatRow, "D").Value = _
                    .Cells(concatRow, "D").Value & vbLf & _
                    .Cells(currentRow, "C").Value

            End If
        Next currentRow
    End With
End Sub