0

我正在使用 excel 打开一个文本文件,找到某个字符串并将其替换为空/删除它。显然,我很难弄清楚星号/通配符的正确语法,希望这对某人来说是一个简单的答案!

这是我的代码的一个简短示例,以防它有一些隐藏的影响。

Sub ReplaceText()
Dim DataFind As String

Open "ORIGINAL\073347.TXT" For Binary As #1
DataFind = Space$(LOF(1))
Get #1, , DataFind
Close #1

                     '<< 073347 >>
DataFind = Replace(DataFind, "<< * >>", "")

Open "NEW\073347.TXT" For Output Access Write As #1
Print #1, DataFind
Close #1

End Sub

基本上我想在文本文件中找到一种特定类型的字符串(语法方面),在这种情况下它将是“<< 073347 >>”但我似乎找不到正确的语法来使用 < < >> 在任何一方,或者一旦我知道我做错了什么,可能会发生其他事情。“<< 073347 >>”工作正常。我尝试过“&”符号、添加空格等,可能只是在正确的上下文中。希望这是足够的信息。并提前感谢!

4

4 回答 4

0

您不能使用 Excel 替换功能进行通配符替换。使用使用正则表达式/vbscript你很可能会有更好的运气

于 2013-02-19T02:25:50.143 回答
0

您可以使用 Mid 函数和循环来处理此问题:

    Sub ReplaceText()
    Dim DataFind As String
    Open "1.TXT" For Binary As #1
    DataFind = Space$(LOF(1))
    Get #1, , DataFind
    Close #1

                         '<< 073347 >>
    While InStr(DataFind, "<<") > 0 And InStr(DataFind, "<<") < InStr(DataFind, ">>")
        DataFind = Mid(DataFind, 1, InStr(DataFind, "<<") - 1) & Mid(DataFind, InStr(DataFind, ">>") + 2, Len(DataFind))
    Wend
    Open "1.TXT" For Output Access Write As #1
    Print #1, DataFind
    Close #1
    End Sub
于 2013-02-19T02:38:37.760 回答
0

Replace 函数仅搜索完全匹配。为了根据模式替换字符串,您应该使用正则表达式。

一个好的开始是教程http://www.macrostash.com/2011/10/08/simple-regular-expression-tutorial-for-excel-vba/。匹配后,使用 Mid() 替换内容。

不要忘记首先通过 Tools --> References 添加“Microsoft VBScript 正则表达式”引用。

于 2013-02-19T02:41:37.543 回答
0

像这样使用正则

Sub ManipulateStrings()
    Dim strIn As String
    Dim objRegex As Object
    'first and last sub-portions are matches, middle missing leading/trailing spaces   
    strIn = "<< 073347 >> ff <<fred>>, << fred >>"
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Global = True
        .Pattern = "<< .+? >>"
        If .test(strIn) Then
            MsgBox .Replace(strIn, vbNullString)
        Else
            MsgBox "No matches"
        End If
    End With
End Sub
于 2013-02-19T03:02:10.040 回答