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

时间:2014-07-15 06:07:42

标签: excel vba excel-vba csv

我正在尝试编写一个宏来自动导入我的工作簿中的csv文件。但是我遇到了解析分隔符的问题,特别是文件系统对象的readline方法在调用时没有读取完整的行

实施例

csv中的一行:

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

什么是readline提取

1,2,jack,"there can be many

这会导致工作表最终成为

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

可能导致此问题的任何想法?

由于

1 个答案:

答案 0 :(得分:1)

最正确的方法是处理和摆脱不可打印的角色,正如Pieter Geerkens建议的那样,或者像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.

我知道更换和计算这种方式感觉非常笨拙。但不知何故,这是VBA。像这样,您不需要正则表达式库,您可以通过添加行直接将您的经验添加到代码中。如果您发现一个令人不安的新角色,只需将其添加到替换线即可。

有人可能会讨论检查最后一行是否更好,而不是检查作为一部分行的部分。但无论如何,如果你在没有任何配额的情况下阅读一小部分(因此cnt > 0),你可能会有一些不确定因素。但是,我们不希望你的档案中毒; - )

祝你好运。

修改

对于计算问题,或许更好的方法是计算逗号,的数量。所以,你可以更准确地衡量"完成"你的行已经。