【问题标题】:InStr delimiter issueInStr 分隔符问题
【发布时间】:2014-06-25 02:37:13
【问题描述】:

我正在解析一个文本文件,其中包含与以下类似的行:

一些文本 (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)

【问题讨论】:

    标签: ms-access parsing vba delimiter


    【解决方案1】:

    我可以建议改用正则表达式吗?如果您导航到 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
    

    【讨论】:

    • 谢谢,但这部分只是我正在编写的大型解析模块的一小部分,并且希望保持与正在解析的其余文本类似的格式。这就是我仍在使用 InStr 函数的原因
    • 好吧,祝你好运!如果有机会,您可能会查看Regular Expressions,因为它们提供了强大的功能来准确指定您想要的内容。也许他们可以在未来的项目中帮助你:)
    【解决方案2】:

    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))
    

    【讨论】:

    • 这适用于文本文件的第一行和最后一行。但由于第二行缺少第二个“-”,我得到一个运行时错误。因为 intKbDelta 是负数
    • 谢谢,就是这样。不得不稍微玩一下并添加一个 IF...Then...Else 语句,但在您的帮助下让它正常工作!
    【解决方案3】:

    一些注释,不适合 SQL,除了作为 UDF,在 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
    

    【讨论】:

      猜你喜欢
      • 2011-04-15
      • 2013-02-10
      • 1970-01-01
      相关资源
      最近更新 更多