拆分,逃避某些分裂

时间:2016-07-13 08:38:33

标签: excel-vba vba excel

我有一个包含多个问题和答案的单元格,其组织方式类似于CSV。因此,为了将所有这些问题和答案分开,使用逗号分隔一个简单的分割,因为分隔符应该很容易将它分开。

不幸的是,有些值使用逗号作为小数分隔符。有没有办法逃避这些事件的分裂?

幸运的是,我的数据可以使用","作为分隔符,但如果不是这样的话,除了手动将小数分隔符从逗号替换为点之外还有解决方案吗?

示例:

"价格:0,09,数量:12,已售:是" 使用拆分("价格:0,09,数量:12,已售出:是",",")将产生:

价格:0
09
数量:12
已售:是

2 个答案:

答案 0 :(得分:0)

给定此测试数据,一种可能性是在拆分后循环遍历数组,并且只要字符串中没有:,就将此条目添加到前一个。

执行此操作的功能可能如下所示:

Public Function CleanUpSeparator(celldata As String) As String()
    Dim ret() As String
    Dim tmp() As String
    Dim i As Integer, j As Integer

    tmp = Split(celldata, ",")
    For i = 0 To UBound(tmp)
        If InStr(1, tmp(i), ":") < 1 Then
            ' Put this value on the previous line, and restore the comma
            tmp(i - 1) = tmp(i - 1) & "," & tmp(i)
            tmp(i) = ""
        End If
    Next i

    j = 0
    ReDim ret(j)
    For i = 0 To UBound(tmp)
        If tmp(i) <> "" Then
            ret(j) = tmp(i)
            j = j + 1
            ReDim Preserve ret(j)
        End If
    Next i

    ReDim Preserve ret(j - 1)

    CleanUpSeparator = ret
End Function

请注意,例如,通过将分隔符caharacters :,纳入参数,还有改进的余地。

答案 1 :(得分:0)

我花了大约24小时左右的时间来解释我认为是一个完全类似的问题,所以我将在这里分享我的解决方案。如果我对我的解决方案对这个问题的适用性有误,请原谅我。 : - )

我的问题:我有一个SharePoint列表,其中教师(我是小学技术专家)输入年终奖励证书供我打印。教师可以输入多个学生&#39;给定奖励的名称,使用逗号分隔每个名称。我在Access中有一个VBA宏,它将每个名称转换为邮件合并的单独记录。好的,我骗了。这更像是一个故事。问题是:教师如何添加学生名字,如Hank Williams,Jr。(请注意逗号),不要使用逗号原因&#34; Jr。&#34;在我的宏中被解释为一个单独的学生?

(SharePoint导出到Excel)字段的全部内容&#34;学生&#34;存储在宏中的一个名为strStudentsBeforeSplit的变量中,该字符串最终用以下语句拆分:

strStudents = Split(strStudentsBeforeSplit,&#34;,&#34;,-1,vbTextCompare)

所以问题确实存在。 Split函数使用逗号作为分隔符,但是可怜的学生Hank Williams,Jr。在他的名字中有一个逗号。怎么办?

我花了很长时间试图找出如何逃避逗号。如果这是可能的,我从来没有弄明白。

许多论坛帖子建议使用不同的字符作为分隔符。我想,那没关系,但这是我提出的解决方案:

  1. 仅替换&#34; Jr&#34;之前的特殊逗号;在拆分功能运行之前,使用不同的,不常见的字符。
  2. 在Split运行后切换回逗号。
  3. 这真的是我的帖子的结尾,但是这里是我的宏完成第1步的行。这可能是也可能不是有意义的,因为它实际上只涉及进行交换的细节。请注意,代码处理了几种不同的(大多数是错误的)我的老师可能会键入&#34; Jr&#34;名称的一部分。

    'Dealing with the comma before Jr.  This will handle ", Jr." and ", Jr" and " Jr." and " Jr".
    'Replaces the comma with ~ because commas are used to separate fields in Split function below.
    'Will swap ~ back to comma later in UpdateQ_Comma_for_Jr query.
    strStudentsBeforeSplit = Replace(strStudentsBeforeSplit, "Jr", "~ Jr.") 'Every Jr gets this treatment regardless of what else is around it.
    'Note that because of previous Replace functions a few lines prior, the space between the comma and Jr will have been removed.  This adds it back.
    strStudentsBeforeSplit = Replace(strStudentsBeforeSplit, ",~ Jr", "~ Jr") 'If teacher had added a comma, strip it.
    strStudentsBeforeSplit = Replace(strStudentsBeforeSplit, " ~ Jr", "~ Jr") 'In cases when teacher added Jr but no comma, remove the (now extra)...
    '...space that was before Jr.