使用VBA对一行文本文件中的逗号进行计数

我有一个excelmacros,我们的财务团队将用它来将excel文件转换为特定格式(逗号分隔txt),以便将数据导入到我们的系统中。 这个macros很好,只有一个例外。 最后的文件需要有5个字段:账号,卡号,date,交易代码,金额。

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

它像这样保存:

1944210004744845,20092014,931,2191.33 

它应该像这样保存:

 ,1944210004744845,20092014,931,2191.33 

只要第一列中有一个帐号,一切都没问题。

我不希望我们的开发人员进行更改,所以我正在考虑在保存txt文件之后在macros的末尾添加一段文件,该文件将计算txt文件第一行中的逗号数,并将IF只有3个逗号,它必须在文件中的每个logging之前添加一个逗号。

有人可能会帮助,因为我不知道该怎么做。 或者也许有更好的办法?

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

在这里输入图像说明

运行这个代码:

 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的新文件,如下所示:

在这里输入图像说明


你不必保存到一个新的文件,但如果出现问题,它可以更容易返回。

计算string中的字符: 计算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