移除宏生成CSV文件时产生的多余尾随逗号
移除CSV生成宏中的多余尾随逗号
你的代码出现尾随逗号,主要是两个原因:一是xlCellTypeLastCell会包含曾经编辑过的最后单元格(哪怕现在是空的),导致循环到空列时也会添加逗号;二是原代码的文件路径拼接存在语法错误,还额外添加了不必要的空格。
修正方案1:优化循环逻辑(兼容旧版本Excel)
修改后的完整代码:
Sub NEWMACRO () Dim complete_rec As String Dim mylogfile As Integer Dim rng As Range Dim lLastRow As Long Dim lLastCol As Long Dim irow As Long Dim icol As Long ' 修正文件路径拼接的语法错误 mylogfile = FreeFile() Open "C:\File\" & Range("A2").Value & ".csv" For Output Access Write As mylogfile ' 使用UsedRange获取真实的已使用数据区域,避免xlCellTypeLastCell返回虚假空列 Set rng = ActiveSheet.UsedRange lLastRow = rng.Row + rng.Rows.Count - 1 lLastCol = rng.Column + rng.Columns.Count - 1 For irow = 1 To lLastRow complete_rec = "" ' 遍历当前行的有效列 For icol = 1 To lLastCol ' 只拼接非空单元格内容,避免空值导致多余逗号 If Application.Cells(irow, icol).Value <> "" Then If complete_rec = "" Then complete_rec = Application.Cells(irow, icol).Value Else complete_rec = complete_rec & "," & Application.Cells(irow, icol).Value End If End If Next icol ' 直接写入处理后的行内容,移除多余空格操作 Print #mylogfile, complete_rec Next irow Close mylogfile End Sub
关键修改点:
- 修复了文件路径的拼接错误,原写法会导致编译报错
- 替换
xlCellTypeLastCell为UsedRange,确保只处理真实有数据的区域 - 添加非空单元格判断,跳过空值,避免生成多余逗号
- 移除了不必要的末尾空格添加操作
修正方案2:用Join函数简化代码(更高效)
利用Join函数直接拼接非空单元格数组,天生不会产生尾随逗号,代码更简洁:
Sub NEWMACRO () Dim mylogfile As Integer Dim rng As Range Dim lLastRow As Long Dim lLastCol As Long Dim irow As Long Dim rowArr As Variant mylogfile = FreeFile() Open "C:\File\" & Range("A2").Value & ".csv" For Output Access Write As mylogfile Set rng = ActiveSheet.UsedRange lLastRow = rng.Row + rng.Rows.Count - 1 lLastCol = rng.Column + rng.Columns.Count - 1 For irow = 1 To lLastRow ' 将当前行的单元格区域转换为一维数组 rowArr = Application.Transpose(Application.Transpose(Range(Cells(irow, 1), Cells(irow, lLastCol)).Value)) ' 过滤数组中的空值 rowArr = Filter(rowArr, "", False) ' 用逗号拼接数组元素,自动无尾随逗号 Print #mylogfile, Join(rowArr, ",") Next irow Close mylogfile End Sub
内容的提问来源于stack exchange,提问作者VIVE TASK
相关产品推荐
相关产品推荐

