InStr分隔符问题

时间:2014-05-07 22:03:18

标签: vba parsing access-vba delimiter

我正致力于解析具有与以下类似的行的文本文件:

  

部分文字(2934418) - KB2933528 - XP x86
  一些文字 - KB2923392
  Sometext - KB2933528 - XP x64 / 2003

(注意: txt文件中没有空行

我尝试使用InStr函数来解析文本并仅获取KB编号,但我似乎无法弄清楚要使用哪些分隔符来执行此操作。自" - "是相同的字符,它保持返回相同的值,而不是找到第二个" - "。这是我现在的代码。

intKbOpen = InStr(1, linedata, "-") intKbClose = InStr(1, linedata, "-") intKbDelta = (intKbOpen - intKbClose) strKb = Mid(linedata, intKbOpen, intKbDelta)

3 个答案:

答案 0 :(得分:3)

我建议使用正则表达式吗?如果您导航到工具--->在VBE中引用,您可以选中" Microsoft Scripting Runtime"旁边的框。这允许您访问可以使用的RegExp类,如下所示:

Public Sub Test()
    Dim oRegExp As RegExp
    Set oRegExp = New RegExp

    Dim oMatches As MatchCollection
    Dim oMatch As Match

    With oRegExp
        .Global = True 'It will find all the matches, not just the first one
        .IgnoreCase = True 'I'm assuming you would still want to capture even if the "kb" is lowercase
        .Multiline = True 'I'm assuming your data may have end-of-line characters in it
        .Pattern = "KB\d+" 'This means, match the letter K, then the letter B, then one or more digits. Ignore everything else.
        Set oMatches = .Execute("Some text (2934418) - KB2933528 - XP x86 Some text - KB2923392 Sometext - KB2933528 - XP x64/2003")
    End With

    For Each oMatch In oMatches
        Debug.Print oMatch
    Next
End Sub

运行此功能会导致以下内容被打印到VBA中的即时窗口:

KB2933528
KB2923392
KB2933528

答案 1 :(得分:1)

InStr的第一个参数是起始位置,因此请更改第二行,并检查是否缺少第二个破折号:

intKbOpen = InStr(1, linedata, "-") + 1
intKbClose = InStr(intKbOpen, linedata, "-")
If intKbClose = 0 Then
   intKbClose = Len(linedata)
   intKbDelta = (intKbClose - intKbOpen) - 1
   strKb = Trim(Mid(linedata, intKbOpen + 1, intKbDelta + 1))
Else
   intKbDelta = (intKbClose - intKbOpen) - 1
   strKb = Trim(Mid(linedata, intKbOpen + 1, intKbDelta))

答案 2 :(得分:1)

除了作为UDF之外,不适合SQL的一些注释,在MS Access之外不可用。

x1 = "Some text (2934418) - KB2933528 - XP x86"
x2 = "Some Text - KB2923392"
x3 = "Sometext - KB2933528 - XP x64/2003"

astrX = Split(x1, "-") '' And so on

For i = 0 To UBound(astrX)
    ''# is any number
    If astrX(i) Like "*KB###*" Then 
        sKB = astrX(i)
    End If
Next

Debug.Print sKB