为了改变行长度,避免CSV导出中的空单元格

我的行没有相同的长度,我需要避免出现在CSV之间的“空白”。 例如,当我输出这个

1 2 3 4 5

1 2

1 3 3 4

1 2 3 4 5

我得到这个:

1,2,3,4,5

1,2 ,,,

1,3,3,4-,

1,2,3,4,5

而且我需要从空的单元格之间移除额外的分隔符。 我已经在运行一个macros导出为CSV,所以如果我能在这个开始的时候“删除”空单元格,我会是最好的。

这个小macros将:

  • 避免创build空的Excel行对应的空CSVlogging
  • 避免尾随逗号

Option Explicit Sub CSV_Makerr() Dim r As Range Dim sOut As String, k As Long, M As Long Dim N As Long, nFirstRow As Long, nLastRow As Long Dim MyFilePath As String, MyFileName As String Dim fs, a, mm As Long Dim separator As String ActiveSheet.UsedRange Set r = ActiveSheet.UsedRange nLastRow = r.Rows.Count + r.Row - 1 nFirstRow = r.Row separator = "," MyFilePath = "C:\TestFolder\" MyFileName = "whatever" Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.CreateTextFile(MyFilePath & MyFileName & ".csv", True) For N = nFirstRow To nLastRow k = Application.WorksheetFunction.CountA(Cells(N, 1).EntireRow) sOut = "" If k = 0 Then Else M = Cells(N, Columns.Count).End(xlToLeft).Column For mm = 1 To M sOut = sOut & Cells(N, mm).Text & separator Next mm sOut = Left(sOut, Len(sOut) - 1) a.writeline (sOut) End If Next a.Close End Sub 

我发现解决起来非常简单,我只是添加了一个循环来检查和删除,如果一行中的最后一个符号是分隔符

 With Selection StartRow = .Cells(1).Row StartCol = .Cells(1).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With Else With ActiveSheet.UsedRange StartRow = .Cells(1).Row StartCol = .Cells(1).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With End If For RowNdx = StartRow To EndRow WholeLine = "" For ColNdx = StartCol To EndCol If Cells(RowNdx, ColNdx).Value = "" Then CellValue = "" Else CellValue = Cells(RowNdx, ColNdx).Value End If WholeLine = WholeLine & CellValue & Sep Next ColNdx WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep)) //I added this to delete the last seperator in a line before printing Dim last As String last = Right(WholeLine, 1) Do Until last <> "," WholeLine = Left(WholeLine, Len(WholeLine) - 1) last = Right(WholeLine, 1) Loop Print #nFileNum, WholeLine Next RowNdx