当我从Excel工作表写入内容时,如何避免文本文件中的换行符?

下面是我写的从excel表格到文本文件的内容的一段VBA代码。

ActiveWorkbook.Sheets("Sheet1").Activate With ActiveSheet .Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)).Select End With Dim strPath As String Dim FSO As Object Dim oFile As Object Set oFile = Nothing Dim c As Range Dim linefeed_remover strPath = "path" Set FSO = CreateObject("Scripting.FileSystemObject") Set oFile = FSO.CreateTextFile(strPath & filesname) For Each c In Selection oFile.Write Application.WorksheetFunction.Clean(c.Value) & vbLf Next c oFile.Close strNameOld = strName & "_Old" 'MsgBox "File Created" 'conn2.Close 

谁能帮我解决这个问题?

build议

  1. 不要循环遍历一个范围内的单元格。 将它们存储在一个数组中并循环访问数组。 这是一个更快的方法。

  2. 使用数组也可以让我们知道我们正在处理哪个logging。 如果我们正在处理最后一条logging,我们可以跳过添加生活提要。

看到这个例子。

 Sub Sample() Dim strPath As String Dim FSO As Object, oFile As Object Dim c As Range Dim linefeed_remover Dim MyAr ActiveWorkbook.Sheets("Sheet1").Activate With ActiveSheet .Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)).Select End With Set oFile = Nothing strPath = "C:\Users\Siddharth\Desktop\" filesname = "Sample.Txt" '~~> Transfer the entire range in an array '~~> For faster performcance MyAr = Selection.Value Set FSO = CreateObject("Scripting.FileSystemObject") Set oFile = FSO.CreateTextFile(strPath & filesname) For i = LBound(MyAr) To UBound(MyAr) '~~> Check if it is the last record so that '~~> We do not add the linefeed If i = UBound(MyAr) Then oFile.Write Application.WorksheetFunction.Clean(MyAr(i, 1)) Else oFile.Write Application.WorksheetFunction.Clean(MyAr(i, 1)) & vbNewLine End If Next i oFile.Close End Sub