使用VBA计算文本文件行中的逗号

时间:2014-09-26 06:29:18

标签: excel excel-vba vba

我有一个excel宏,我们的财务团队将使用它将excel文件转换为特定格式(逗号分隔的txt),以便他们可以将数据导入我们的系统。宏有效,但有一个例外。最终文件需要有5个字段:帐号,卡号,日期,交易代码,金额。

只有帐号或卡号是强制性的 - 您不需要两者。问题是,当将Excel文件保存为逗号分隔文件(手动或使用宏)并且没有帐号(即所有记录仅使用卡号)时,第一列为空(文件没有标题),然后以逗号分隔文件保存,只有4个字段,从卡号开始 - 它应该以空白字段开头,即带有 立即逗号 - 我们的系统现在拒绝这些文件。

它像这样保存:

1944210004744845,20092014,931,2191.33

它应该像这样保存:

,1944210004744845,20092014,931,2191.33

只要第一列中某处有一个帐号,一切都可以。

我不希望我们的开发人员进行更改,所以我想在保存txt文件之后在宏的末尾添加一个部分,这将计算第一行中逗号的数量。 txt文件,如果只有3个逗号,则必须在文件中的每个记录之前添加一个逗号。

有人可能会对此有所帮助,因为我不知道该怎么做。或许还有更好的方法?

2 个答案:

答案 0 :(得分:1)

从名为'myFile.txt'的文件开始,该文件位于C:\ Temp目录中,如下所示:

enter image description here

运行此代码:

Sub readTXT()
    Dim FilePath As String
    Dim strFirstLine As String

    FilePath = "C:\temp\myFile.txt"

    'Load txt file into array
    Open FilePath For Input As #1
    dataArray = Split(Input$(LOF(1), #1), vbLf)
    Close #1

    'Test first line if it has three commas
    If Len(dataArray(0)) - Len(Replace(dataArray(0), ",", "")) = 3 Then
        'Add comma to start of strings
        For i = LBound(dataArray) To UBound(dataArray)
            dataArray(i) = "," & dataArray(i)
        Next i

        'Creat new file
        FilePath = Left(FilePath, Len(FilePath) - 4) & "_Comma.txt"
        Open FilePath For Output As #2

        'Write to new file modified data
        For Each Line In dataArray
            Print #2, Line
        Next Line

        Close #2
    End If
End Sub

结果是一个名为myFile_Comma.txt的新文件,如下所示:

enter image description here


您不必保存到新文件,但如果出现问题,则可以更轻松地返回。

答案 1 :(得分:0)

计算字符串中的字符数: Count specific character occurrences in string

逐行遍历整个文件:

dim c as Range
Set c = Range("A1")
do until IsEmpty(c.Value)
   if countTheCharacters(c.Value,",") < 3 then
     c.Value = "," & c.Value
   end if
   set c = c.Offset(1,0)
loop
相关问题