从Excel中的无序数据中提取相关列的相关数据

时间:2016-04-27 05:57:00

标签: excel excel-vba vba

我在excel的A列(单元格A2,A3,A4)中按以下方式获得数据

  1. Apple 223 12袋32胡萝卜4231 2321甜甜圈5231 232 1321大象6232
  2. Apple 3123213 Bags 412321 3213 Carrots 411 Donuts 621 3213 Elephants 71 2321
  3. Apple 212324 Carrots 52312 Bags 42313 Elephants 512312 Donuts 621 32132
  4. 我需要将此数据提取到相关的列A,B,C,D,E。 到目前为止已经能够提出以下解决方案。

    • 在第一行插入列标题A,B,C,D,E,Dummy(即B1,C1,D1,E1,F1,G1)
    • 将以下公式放入行2,3,4

      的相应单元格中
       =MID($A2,FIND(E$1,$A2)+LEN(E$1),IFERROR(FIND(F$1,$A2),LEN($A2)+1)-FIND(E$1,$A2)-LEN(E$1))
      

    这适用于数据集1,2,其中数据是有序的,即A然后B然后是C依此类推

    但它不适用于数据集3,其中数据是无序的,即A然后是C然后是B然后是E然后是D ..如下所示。任何建议表示赞赏 - 我也对VBA解决方案持开放态度。感谢。

    TexttoCols

1 个答案:

答案 0 :(得分:2)

我认为你的公式太复杂了,因为你把它解决了......

enter image description here

Cell B2包含(填充和跨越)......

=IF(ISERROR(FIND(B$1,$A2)),"",MID($A2,FIND(B$1,$A2)+2, 1))

此解决方案依赖于数字部分只有一个字符长的事实。

针对修改后的要求进行了更新

在B2中使用此公式(填充和跨越)...

=IF(ISERROR(FIND(B$1,$A2)),"",MID($A2,FIND(B$1,$A2)+2, IF(ISERROR(FIND(" ",$A2,FIND(B$1,$A2)+2)-(FIND(B$1,$A2)+2)),LEN($A2),FIND(" ",$A2,FIND(B$1,$A2)+2)-(FIND(B$1,$A2)+2))))

......对于这个结果......

enter image description here

此解决方案依赖于列名(A,B等)与数字之间的空格以及列名称的单个字符。

针对修改后的要求进行了更新

在B2中使用此公式(填充和跨越)...

=IF(ISERROR(FIND(B$1,$A2)),"",MID($A2,FIND(B$1,$A2)+LEN(B$1)+1, IF(ISERROR(FIND(" ",$A2,FIND(B$1,$A2)+LEN(B$1)+1)-(FIND(B$1,$A2)+LEN(B$1)+1)),LEN($A2),FIND(" ",$A2,FIND(B$1,$A2)+LEN(B$1)+1)-(FIND(B$1,$A2)+LEN(B$1)+1))))

对于这个结果......

enter image description here

针对修改后的要求进行了更新

用户定义的函数对于这个问题来说要简单得多。

以下VBA用户定义函数(UDF)...

Function FindData(DataString As String, SearchString As String, AllSearchStrings As Range) As String
Dim iLoop As Long, iTemp As Long, iStart As Long, iEnd As Long
Dim oCell As Range
' Initialize
    FindData = ""
    If DataString = "" Then GoTo Done
    If SearchString = "" Then GoTo Done
    If AllSearchStrings.Cells.Count = 0 Then GoTo Done

' find where in the data string the data starts
    On Error Resume Next
        iStart = WorksheetFunction.Find(SearchString, DataString, 1) + Len(SearchString) + 1
    On Error GoTo 0
    If IsError(iStart) Or iStart = 0 Then GoTo Done

' find where in the data string the data ends
    iEnd = Len(DataString) + 1
    For Each oCell In AllSearchStrings
        On Error Resume Next
            iTemp = WorksheetFunction.Find(oCell.Value, DataString, 1)
        On Error GoTo 0
        If IsError(iTemp) Then
            iTemp = Len(DataString) + 1
        Else
            If iTemp < iStart Then iTemp = Len(DataString) + 1
            If iTemp < iEnd Then iEnd = iTemp
        End If
    Next oCell

' extract the string
    FindData = Trim(Mid(DataString, iStart, iEnd - iStart))
Done:
End Function

...在Cell B2中调用(填充并跨越)...

=FindData($A2,B$1,$B$1:$G$1)

...并获得此结果......

enter image description here