VBA在特定模式后搜索列中的值

时间:2016-11-09 13:39:18

标签: string vba

我输入的数据如下:

gen,N,,,GONGD,,,N,,,KL,0007bd,,,,,,,,TAK,
gen,N,,,RATEC,,,N,,,KP,0007bc,,,,,,,,TAZ,
kap,N,,,EBFWE,N,,,,,,,,,KP,002bd4,,,KP,123000,,,,,N,,,,P
kap,N,,,ST,WEIT,E3,EBFWEI,,,KP,002bd2,N,,,,,,KP,002bd3,,,,,,,Z,MG00,,,,,N,,,,P

一行在一列中。首先,我需要知道我以“kap”开头,然后我需要在第一个“,KP”之后保存6个字符(或数字)作为“Variable1”,并在第二个之后保存6个字符或数字“ ,KP,“as”Variable2“。请帮助我,我无望。

预期结果:第一个“kap”行的Var1 = 002bd4,Var2 = 123000。 Var3 = 002bd2,Var4 = 002bd3

我试过这个,知道我在“kap”起跑线:

Sub Find()
Dim rFoundAddress As Range
Dim sFirstAddress As String
Dim x As Long

With ThisWorkbook.Worksheets("Sheet1").Columns(1)
    Set rFoundAddress = .Find("kap,*", LookIn:=xlValues, LookAt:=xlWhole)
    If Not rFoundAddress Is Nothing Then
        sFirstAddress = rFoundAddress.Address
        Do


            Set rFoundAddress = .FindNext(rFoundAddress)
        Loop While Not rFoundAddress Is Nothing And _
            rFoundAddress.Address <> sFirstAddress
    End If
End With
End Sub

谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个

Sub Find()
    Dim rFound As Range
    Dim sFirstAddress As String
    Dim vals As Variant

    With ThisWorkbook.Worksheets("Sheet1").Columns(1)
        Set rFound = .Find("*kap,*", LookIn:=xlValues, LookAt:=xlWhole)
        If Not rFound Is Nothing Then
            sFirstAddress = rFound.Address
            Do
                vals = Split(Split(Split(rFound.text, "KP")(1), ",")(1) & "," & Split(Split(rFound.text, "KP")(2), ",")(1), ",")
                Set rFound = .FindNext(rFound)
            Loop While rFound.Address <> sFirstAddress
        End If
    End With
End Sub

在每一行,你都会得到vals数组,在那行中存储两个想要的值