VBA Excel替换单元格中的换行符

时间:2016-12-01 16:13:29

标签: excel vba excel-vba

我需要替换单元格中的换行符,换行符和活动单元格同一列中单元格的内容。

代码将是这样的:

 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

我试图用两种方法替换换行符的值,替换和替换。他们都没有工作,或者我对这段代码做错了。

数组arColumns具有我想要工作的列范围,例如:B:C,E:E,M:O,Z:AB ...

1 个答案:

答案 0 :(得分:0)

以及您已被告知的vbLf修正,您可以按以下方式重构代码:

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