对于不同的行长度,请避免CSV导出中的空单元格

时间:2016-01-27 12:25:03

标签: excel excel-vba csv vba

我的行长度不一样,我需要在导出为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

我需要从之间的空单元中删除额外的分隔符。 我已经在运行一个宏来导出为CSV,所以如果我可以在此开头“删除”空单元格,那将是最好的。

2 个答案:

答案 0 :(得分:1)

这个小宏将:

  • 避免创建与空Excel行相对应的空 CSV 记录
  • 避免使用逗号


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

答案 1 :(得分:0)

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

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
相关问题