【问题标题】:Excel, Vba, Asterisk, Syntax, text fileExcel、Vba、Asterisk、语法、文本文件
【发布时间】:2013-02-19 02:18:12
【问题描述】:

我正在使用 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

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

【问题讨论】:

    标签: regex excel vba replace


    【解决方案1】:

    您可以使用 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
    

    【讨论】:

    • 谢谢。所有的答案都非常有帮助。使用 mid 函数绝对是最不令人失望的,但我最终可能会依赖一些 RegEx 的东西。谢谢你们三个。
    • 对这个反应有点惊讶 - RegExp 可以运行单次替换而不是潜在的冗长的中间循环。
    【解决方案2】:

    您不能使用 Excel 替换功能进行通配符替换。使用Using Regex / vbscript,您很可能会获得更好的运气

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

        类似这样的使用

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-13
          • 2015-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多