在单个单元格中添加换行符

时间:2015-01-07 04:08:05

标签: excel vba excel-vba

我现在尝试找到一个解决方案。 我每月生成特定报告,并使用此报告自动生成发票。

其中一个报告单元格包含与此类似的数据

Contract Ref: #Service Schedule 001 Site A: No, 22, ABC Road,City A: TSV Site 
B: Home exchange  City B: TSV Service ID: xxxxxxxxxxx W/O: 123 Capacity: Multiple

我需要强制换行到所有这些看起来像这样的单元格。

Contract Ref: #
Service Schedule 001 
Site A: No, 22, ABC Road, 
City A: TSV 
Site B: Home exchange  
City B: TSV 
Service ID: xxxxxxxxxxx 
W/O: 123 
Capacity: Multiple

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

您可以使用以下UDF

Function SplitText(r As Range) As String

Dim i As Integer, ii As Integer

    i = Application.Find("Service S", r)
    SplitText = SplitText & Left(r, i - 1) & vbLf
    ii = Application.Find("Site A", r)
    SplitText = SplitText & Mid(r, i, ii - i) & vbLf
    i = Application.Find("City A", r)
    SplitText = SplitText & Mid(r, ii, i - ii) & vbLf
    ii = Application.Find("Site B", r)
    SplitText = SplitText & Mid(r, i, ii - i) & vbLf
    i = Application.Find("City B", r)
    SplitText = SplitText & Mid(r, ii, i - ii) & vbLf
    ii = Application.Find("Service ID", r)
    SplitText = SplitText & Mid(r, i, ii - i) & vbLf
    i = Application.Find("W/O", r)
    SplitText = SplitText & Mid(r, ii, i - ii) & vbLf
    ii = Application.Find("Capacity", r)
    SplitText = SplitText & Mid(r, i, ii - i) & vbLf
    SplitText = SplitText & Right(r, Len(r) - i + 1)

End Function

在目标单元格中​​输入公式后,您需要将目标单元格格式化为自动换行。

e.g。如果文本在A1中并且目标单元格是A4,则在A4中将 = SplitText(A1)和格式A4放到文本中。

答案 1 :(得分:0)

要通过VBA在Excel中添加换行符,您必须使用Chr(10)

例如,下面的代码在所选单元格中的每个字符后添加换行符。

您必须找到告诉代码的方法,在哪里插入换行符的适当位置。

Sub insert_nl()
    Dim rng As Range
    Set rng = Selection
    Dim ic As Integer, nc As Integer
    Dim s1 As String, s2 As String
    s1 = rng.Value
    nc = Len(s1)
    s2 = ""
    For ic = 1 To nc - 1
        s2 = s2 & Mid(s1, ic, 1) & Chr(10)   ' This line adds the newline character
    Next ic
    s2 = s2 & Mid(s1, nc, 1)
    rng.Value = s2
End Sub

答案 2 :(得分:0)

这是一种略有不同的方法:

Option Explicit

Private Const sFldNames = ",Contract Ref:,Service Schedule,Site A:,City A:,Site B:,City B:,Service ID:,W/O:,Capacity:"

'Call this Sub with the parameters supplied and it is done
Private Sub SplitReportString(sRpt As String, sTabName As String, row As Long, col As Long)
'sTabName is the worksheet's name you want to write your output to
'row and col is where you want to start writing your output at
    Dim vFldNamesArray As Variant
    Dim i As Long
    Dim vRptArray As Variant

    vFldNamesArray = Split(sFldNames, ",")
    For i = 1 To UBound(vFldNamesArray, 1)
        sRpt = Replace(sRpt, vFldNamesArray(i), "," & vFldNamesArray(i))
    Next
    vRptArray = Split(sRpt, ",")
    With ThisWorkbook.Worksheets(sTabName)
        For i = 1 To UBound(vRptArray)
            .Cells(row + i - 1, col) = vRptArray(i)
        Next
    End With
End Sub