【问题标题】:How to breakdown text with a non-uniform delimiter?如何使用非统一分隔符分解文本?
【发布时间】:2014-11-12 02:11:12
【问题描述】:

我在 Excel 中有这些数据:

但我的一位客户需要它详细总结每个项目。
所以上面的数据需要转换成:

这样,客户可以按跟踪和每个项目对其进行分析。
文本格式不是很统一,因为是手动输入的。
一些用户使用 Alt+Enter 来分隔项目。有些使用空间,有些根本不打扰分离。但一致的是,他们将连字符(-)放在项目之后,然后是计数(尽管并不总是跟在数字后面,但两者之间可以有空格)。此外,如果该项目的计数是一 (1),他们根本不会费心放置它(如 Apple Juice 的跟踪 IDU3004 中所见)。

我尝试的唯一功能是 Split 功能,它让我更接近我想要的。
但是我仍然很难将单个数组元素分成我所期望的。
所以例如上面的IDU3001在使用Split(以“-”作为分隔符)后将是:

arr(0) = "苹果" arr(1) = "20 颗葡萄" arr(2) = "5" & Chr(10) & "Pear" ~~> 只是为了显示 Alt+Enter arr(3) = "3香蕉" arr(4) = "2"

当然我可以想出一个函数来处理每个元素来提取数字和项目。
实际上,我正在考虑只使用该功能并完全跳过 Split
我只是好奇,也许还有另一种方法,因为我不精通 Text 操作。
如果有任何想法可以为我指出一个可能的更好的解决方案,我将不胜感激。

【问题讨论】:

  • 一般来说,这看起来很适合正则表达式。但我看到一个问题:混合多词名称和没有数字(计数为 1)。例如Apple Pie - 2 一个Apple 和两个Pies,还是两个Apple Pies?
  • @chrisneilsen 也是。虽然该项目通常是最后输入的项目,但仍然会违反规则。

标签: vba excel split


【解决方案1】:

我建议使用正则表达式方法

这是基于您的示例数据的演示。

Sub Demo()
    Dim re As RegExp
    Dim rMC As MatchCollection
    Dim rM As Match
    Dim rng As Range
    Dim rw As Range
    Dim Detail As String

    ' replace with the usual logic to get the range of interest
    Set rng = [A2:C2]

    Set re = New RegExp

    re.Global = True
    re.IgnoreCase = True
    re.Pattern = "([a-z ]+[a-z])\s*\-\s*(\d+)\s*"
    For Each rw In rng.Rows
        ' remove line breaks and leading/trailing spaces
        Detail = Trim$(Replace(rw.Cells(1, 3).Value, Chr(10), vbNullString))

        If Not Detail Like "*#" Then
            ' Last item has no - #, so add -1
            Detail = Detail & "-1"
        End If

        ' Break up string
        If re.Test(Detail) Then
            Set rMC = re.Execute(Detail)
            For Each rM In rMC
                ' output Items and Qty's to Immediate window
                Debug.Print rM.SubMatches(0), rM.SubMatches(1)
            Next
        End If
    Next
End Sub

根据您的评论,我假设只有 最后一个 单元格中的项目可能缺少-#

示例输入

Apple Juice- 20 Grape -5
pear- 3Banana-2Orange

产生这个输出

Apple Juice   20
Grape         5
pear          3
Banana        2
Orange        1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 2012-12-03
    相关资源
    最近更新 更多