简体   繁体   中英

VBA Excel replace line breaks in a cell

I would need to replace the line breaks in a cell, with a line break and the content of a cell in the same column of the active cell.

The code would be something like this:

 For i = LBound(arColumns) To UBound(arColumns)
   'ActiveColumn = arColumns(i)
   Set rng = Range(arColumns(i))

   For Each Cell In rng.Cells
     If Cell.row > 4 And Cell.row < r Then
       colnum=cell.column
       Cell.value = "{Something}" & Cells(3, colnum).value & _
           ", text here{/something}" & Cell.value  'First line in the cell
       cell.replace what:=vbCrLf, replacement:=vbCrLf & "{Something}" & _
           Cells(3, colnum).value & ", text here{/something}" 'First try
       Cell.value = Application.WorksheetFunction.Substitute(CStr(Cell.value), vbCrLf, vbCrLf & _
           "{maxlen}{/maxlen}{notes}" & ", No Max length{/notes}")  'Second try
     End If
   Next
 Next

I've tried to replace the values of the line breaks with the two methods, replace and substitute. None of them have been working or I am doing something wrong with this block of code.

The array arColumns have the range of columns that I want to work, for example: B:C,E:E,M:O,Z:AB...

along with the vbLf fix you've already been told, you could refactor your code as follows:

Option Explicit

Sub main()
    Dim arColumns As Variant
    Dim cell As Range
    Dim r As Long, i As Long

    arColumns = Array("B:C", "E:E", "M:O", "Z:AB")
    r = 10 '<--| just to have a value to test with
    For i = LBound(arColumns) To UBound(arColumns)
        For Each cell In Intersect(Range(arColumns(i)), Rows("4:" & r)).SpecialCells(xlCellTypeConstants) '<--| loop through current columnns group not empty cells from row 4 to 'r'
            cell.Replace what:=vbLf, replacement:=vbLf & "{Something}" & Cells(3, cell.Column).Value & ", text here{/something}" 'First try
        Next
    Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM