2016-12-01 259 views
0

我需要用換行符和活動單元格的同一列中單元格的內容替換單元格中的換行符。VBA Excel替換單元格中的換行符

的代碼將是這樣的:

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 ...

+2

通常在單元格中的換行符不是vbCrLf,而只是vbLf(換行符)。 –

+1

我不會使用Cell.replace函數,但在純VBA中執行:'Replace(oldValue,vbCrLf,replace)' 這也有助於稍後的重構以顯着提高執行速度。 – pintxo

+0

我不知道爲什麼我沒有想到替換。謝謝。 另外,感謝您的建議文森特,我已經改變它的vbLf,它的工作。 – TMikonos

回答

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 
相關問題