vba excel FileSystemObject readline函数不会读取完整的行

我正在尝试编写一个macros来自动导入我的工作簿的csv文件。 不过,我遇到了parsing分隔符的问题,具体来说,文件系统对象的readline方法在被调用时不会读取完整的行

csv中的一行:

1,2,jack,"there can be many boys in the room"3,4,test,na 

readline摘录

 1,2,jack,"there can be many 

这导致表单结束

 1 | 2 | jack |there can be may boys in the room| 3 | 4 | test | na 

任何想法可能会导致这个问题?

谢谢

最恰当的方法是处理和摆脱不可打印的字符,如彼得·杰尔肯斯(Pieter Geerkens)所build议的那样,或者像帕特里克(PatricK)推荐的那样阅读所有内容并拆分。 但是,如果真的有一些意想不到的换行符,那么最终可能会再次产生太多碎片。

因此,这是一个提示,如何让你的阅读在语义层面更健壮。

这个想法是读一行,并决定是否是一个完整的行:

 ... var line as String var lineFinished as boolean ' Loop starts here ... lineFinished = false ... ' Read a line, or a piece of it. linePiece = a.ReadLine ' or similar ... ' Now let's count the number of quotas: dim cnt as integer cnt = 0 for i=1 to len(line) if mid(line, 0, i) = """" then cnt = cnt + 1 end if next ' If there is an odd number of quotas, the line is not finished: lineFinished = (cnt mod 2 = 0) and (cnt > 0) ' If the line is finished, then take it as a full line. Otherwise, add the pieces up. if lineFinished then lineFinal = linePiece else lineFinal = lineFinal & linePiece end if ... ' Then, use this place to clean the line from other nasty chars: line = replace(line, "\n", "") line = replace(line, "\r", "") line = replace(line, "\t", "") ... ' Then, put your lineFinal to the whole string and reset the variable for the next loop. 

我知道replace和计算这种方式感觉非常笨拙。 但不知何故,这是VBA。 像这样,你不需要正则expression式库,你可以通过添加行直接添加你的经验到代码。 如果你发现一个新的字符干扰,只需将其添加到replace线。

有人可能会讨论是否最好检查最后一行是否完成,而不是检查是否只是行的一部分。 但是,不pipe怎么说,如果你阅读一个没有配额的非常小的文件(因此cnt > 0 ),你可能会有一些不确定性。 但我们不希望你的文件被毒害;-)

祝你好运。

编辑:

在计数方面,也许更好的方法是计算逗号的数量。 所以,你可以更精确地测量你的线路已经“完成”了。