【问题标题】:Replace 2 double quotes into 1 double quote during data load from csv file in VBA在从 VBA 中的 csv 文件加载数据期间将 2 个双引号替换为 1 个双引号
【发布时间】: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


【解决方案1】:

此双引号是特定于语言的。如果这些是您想要避免的唯一字符并且您没有任何其他“奇怪”字符,那么您可以在 Excel 中遍历单元格的字符并检查它们是否是非标准的(例如,不是前 128 个 ASCII 字符):

Public Sub TestMe()

    Dim stringToEdit    As String
    Dim cnt             As Long
    Dim myCell          As Range
    Dim newWord         As String

    For Each myCell In Range("A1:A2")
        newWord = vbNullString
        For cnt = 1 To Len(myCell)
            Debug.Print Asc(Mid(myCell, cnt, 1))
            If Asc(Mid(myCell, cnt, 1)) >= 127 Then
                'do nothing
            Else
                newWord = newWord & Mid(myCell, cnt, 1)
            End If
        Next cnt
        myCell = newWord
    Next myCell

End Sub

因此,假设您有这样的输入:

它会意识到,引号有点奇怪,不应该包含在原始文本中,因为它们不是 ASCII 表中前 128 个单元的一部分。

运行代码后,您会得到一个空单元格和 75823。

【讨论】:

  • 我不是从 Excel 工作表而是从 csv 文件通过代码直接将数据加载到数组中 Open dataFilePath For Input As #1 等等...。我不希望此代码块与 Excel 工作簿表无关,因为它取决于用户 Excel 设置可能会损坏重要数据(可能会因字符串的请求而丢失 0 - 例如邮政编码、电话号码,可能会丢失一些符号) .
猜你喜欢
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多