分割函数 - 按字符串分割单元格

sta*_*ser 6 excel vba

我试图将合并的信息从一个单元格划分为单独的单元格。

一个单元格:

数量:2 价格:253,18 价格2:59,24 欧盟状态:WBB NAS MRR OWA PXA 最低:1 选择:3 类别:PNE 代码 z:195750

分割数据:(我想将每个部分导出到另一个单元格中)

数量:2 价格:253,18 价格 2:59,24 欧盟 状态:WBB NAS MRR OWA PXA 分钟:1 选项:3 类别: PNE 代码 z:195750

我不能简单地通过查找空格、区分大小写的状态单元格来划分| 状态:WBB NAS MRR OWA PXA| 具有不同的数据范围,其中包含无法分割的空格。

拆分(表达式 [,delimiter] [,limit] [,compare] )

    Sub Split_VBA()
'Create variables
Dim MyArray() As String, MyString As String, N As Integer, Temp As String

MyString = B2 ' TRYING TO GET DATA FROM CELL B2 TO SPLIT IT
'Use the split function to divide the string using a string "price:"
MyArray = Split(MyString, "price:")

    Dim arr() As String
    ' Split the string to an array
    arr = Split(B2, "price:") 'try to divide first part of data when appears string 'price:'

   For N = 0 To UBound(MyArray)
     'place each array element plus a line feed character into a string
    Temp = Temp & MyArray(N) & vbLf
Next N
'   I WOULD LIKE TO PROVIDE RESULT IN A ROW NOT IN A COLUMN
Range("A1") = Temp

End Sub
Run Code Online (Sandbox Code Playgroud)

到目前为止,这个 VBA 代码似乎有点超出我的能力,据我检查一些在线可用的示例,尝试提供如下代码,但我被卡住了,我在此向亲爱的社区寻求一些建议。

Ale*_* K. 5

由于顺序相同,一种方法是简单地搜索相邻的键名并解析中间的内容:

Sub g()

    Dim stringValue As String
    
    stringValue = "amount:2 price:253,18 price2:59,24 EU status:WBB NAS MRR OWA PXA min:1 opt:3 category: PNE code z:195750"
    
    Debug.Print getPart(stringValue, "amount", "price")
    Debug.Print getPart(stringValue, "price", "price2")
    Debug.Print getPart(stringValue, "price2", "status")
    Debug.Print getPart(stringValue, "status", "min")
    Debug.Print getPart(stringValue, "min", "opt")
    Debug.Print getPart(stringValue, "opt", "category")
    Debug.Print getPart(stringValue, "category", "code z")
    Debug.Print getPart(stringValue, "code z", "", True)

End Sub

Function getPart(value As String, fromKey As String, toKey As String, Optional isLast As Boolean = False) As String
    Dim pos1 As Long, pos2 As Long
    
    pos1 = InStr(1, value, fromKey & ":")
    
    If (isLast) Then
        pos2 = Len(value)
    Else
        pos2 = InStr(pos1, value, toKey & ":")
    End If
    
    getPart = Trim$(Mid$(value, pos1, pos2 - pos1))
End Function
Run Code Online (Sandbox Code Playgroud)
amount:2
price:253,18
price2:59,24 EU
status:WBB NAS MRR OWA PXA
min:1
opt:3
category: PNE
code z:19575
Run Code Online (Sandbox Code Playgroud)