CSV格式的数据提取末尾的逗号

时间:2015-06-05 00:59:49

标签: excel vba csv

关于我的问题的一点背景:

我有一个由MS Access中的查询创建的CSV文件。 CSV文件的主体包含列;名称,地址,邮政编码,日期等。文件的最后一行包含数据摘要;文件名,日期,时间戳和记录总数。由于所有字段都包含字符串,并且我们不希望系统截断或尝试评估日期和发布代码,因此我们使用引号输出这些字段。

最后两行看起来像这样:

"Name","Code","Address","Address2","Office","Location","City","State","PostCode","Date"
"FileName","DDMMYYYY","HH:MM:SS",TotalRecords,"","","","","",""

我需要删除最后一行中的额外逗号,所以看起来像这样:

"FileName","DDMMYYYY","HH:MM:SS",TotalRecords

我已经仔细检查并尝试了解决方案: CSV file has extra commas

这将创建我原始文件的副本,但保留所有逗号。如果我删除所有引号,此解决方案将起作用。

3 个答案:

答案 0 :(得分:0)

如果您在Excel中,可以在VBA中执行以下单行:

left(Activecell.text,len(trim(replace(replace(activecell.Text,","," "),""""," "))))

我将从中间解释:

replace(replace(activecell.Text,","," "),""""," ")

用空格替换所有逗号和双引号

trim(replace(replace(activecell.Text,","," "),""""," "))

修剪它,即删除起始和尾随空格

len(trim(replace(replace(activecell.Text,","," "),""""," ")))

获取修剪文本的长度

left(Activecell.text,len(trim(replace(replace(activecell.Text,","," "),""""," "))))

最后给我ORIGINAL字符串的左侧部分,将char计数设置为我们计算出的长度减去逗号和开头和结尾的双引号。

答案 1 :(得分:0)

如果字符串以未知数量的逗号或未知数字结尾:

,""

例如:

whatever,,,,,,,"","",,,,"",""

然后这段 VBA 代码将删除那个垃圾:

Sub StringCleaner()
   Dim s1 As String, sTest As String, sOut As String
   s1 = "," & Chr(34) & Chr(34)
   sTest = "whatever" & ",,,,,," & s1 & s1 & ",,," & s1 & s1
   sOut = sTest

   While Right(sOut, 1) = "," Or Right(sOut, 3) = s1
      If Right(sOut, 1) = "," Then sOut = Mid(sOut, 1, Len(sOut) - 1)
      If Right(sOut, 3) = s1 Then sOut = Mid(sOut, 1, Len(sOut) - 3)
   Wend

MsgBox sTest & vbCrLf & sOut
End Sub

答案 2 :(得分:0)

感谢大家的帮助。

我使用了不同的路线来解决我的问题。我创建了一个批处理脚本,它提取记录并将数据重新打印到一个新文件中,省略了文件末尾的额外逗号。

我的代码如下,任何对其进行改进的批评都表示赞赏。

echo off
setlocal EnableDelayedExpansion
pause
set cur=0
FOR /F "delims=" %%A in (input.csv) DO (
    set line=%%A
    set line=!line:,,=, ,!

FOR /F "tokens=1-11 delims=," %%G in (^"!line!^") DO (
    if "%%G"=="" (echo.)
    if "%%G"==""FILENAME"" (
        echo %%G,%%H,%%I,%%J >> test_%date:~-4,4%%date:~-7,2%%date:~-10,2%.csv
        goto EOF
    ) else (
        echo %%G,%%H,%%I,%%J,%%K,%%L,%%M,%%N,%%O,%%P,%%Q >> test_%date:~-4,4%%date:~-7,2%%date:~-10,2%.csv
    )
    set /a cur=cur+1
)
)
    :EOF
    echo %cur%
    pause