【发布时间】:2018-06-03 06:32:40
【问题描述】:
我将 csv 文件中的行加载到数组中(打开 dataFilePath For Input As #1 等等……)。加载的数组数据用 2 个双引号括起来。示例:“”””(空字符串)、“”myText””、“”75823””。问题是后面的代码程序无法正确检测空数组元素或其他数据。我找到了如何将字符串开头和字符串末尾的 2 个双引号替换为 1 个双引号的方法:
For i = 0 To lastArrayIndex
thisString = columnsDataInThisLine(i)
theFirstStringSymbol = Left(thisString, 1)
If theFirstStringSymbol = """" Then
'Replace double double quotes in the string beginning and _
'the end into single double quotes
thisString = Mid(thisString, 2, Len(thisString) - 2)
End If
columnsDataInThisLine(i) = thisString
Next i
在这段代码之后,我得到了我需要的东西 - 示例:“”(空字符串)、“myText”、“75823”,但也许我在从 csv 文件加载数据期间遗漏了一些东西(编码或其他东西)。在读取 csv 文件期间,在加载到数组字符串的开头和结尾删除这 2 个双引号可能是更简单的方法?
【问题讨论】:
-
稍微跑题了;在 VBA 中,您可以使用 FileSystemObject。它比旧的
Open x For Input AS #1更简单、更强大。假设您有一条看起来有点像Split(CurrentLine, ",")的行,您可以替换为:Split(Replace(CurrentLine, """", ""), ",")。小心。引号可用于覆盖逗号。在此示例中,只有两列:"Column one, which contains a comma", "Column two"。 -
别忘了,你必须转义双引号...
a = """"和b = """"""...a是"...b是"" -
根据目标数据评论:在我加载的数据中,引号中有很多逗号。我用 Regex.Pattern = """[^""]*""|[^,]*" 克服了这个问题,因为使用拆分功能我没有找到解决方案。也许 FileSystemObject 是一些参数,或者在 VBA 库中类似于 .NET 中的类似 TextFieldParser?
标签: vba csv double-quotes