在VBA寻找XX / XX @ - @ XX:XX @ - @

时间:2014-03-18 14:45:25

标签: vba excel-vba excel

我想要删除所有具有此格式的字符:XX / XX @ - @ XX:XX @ - @,其中X可以是任意数字。

我尝试用这个程序来解决这个问题:

Sub Date_Time()
'
' It will looking for "/" and delete 16 characters, starting 3 characters before "/".
' It should remove all Date and Time in the file.
'
With Sheets("Get_Command")
.Select

Lastrow = .UsedRange.Rows.Count

    For Lrow = 1 To Lastrow Step 1

        Set find2 = Cells(Lrow, 1).Find("/", LookIn:=xlValues) ' Look for "/"

        If Not find2 Is Nothing Then

            Cells(Lrow, 17).FormulaR1C1 = "=SEARCH(""/"",RC[-16])"
            Cells(Lrow, 18).FormulaR1C1 = "=MID(RC[-17],RC[-1]-2,RC[-1]+13)"

            Cells(Lrow, 1).Replace _
                What:=Cells(Lrow, 18).Value, Replacement:="", _
                LookAt:=xlPart, SearchOrder:=xlByColumns


        End If

    Next Lrow

Columns("Q:R").Select
Selection.Delete Shift:=xlToLeft

End With

End Sub

该程序是,它正在查找行中的第一个“/”,并且可能有一些“/”表示它不是我要删除的格式。

有人知道我该如何解决它?

谢谢,

1 个答案:

答案 0 :(得分:0)

我相信您正在寻找的正则表达式是:

[0-9]{2}\/[0-9]{2}\@\-\@[0-9]{2}:[0-9]{2}\@\-\@

以下是从here获取的通用函数:

Function RegExpReplace(ByVal WhichString As String, _
                        ByVal pattern As String, _
                        ByVal ReplaceWith As String, _
                        Optional ByVal IsGlobal As Boolean = True, _
                        Optional ByVal IsCaseSensitive As Boolean = True) As String
    'Declaring the object
    Dim objRegExp As Object

    'Initializing an Instance
    Set objRegExp = CreateObject("vbscript.regexp")

    'Setting the Properties
    objRegExp.Global = IsGlobal
    objRegExp.pattern = pattern
    objRegExp.IgnoreCase = Not IsCaseSensitive

    'Execute the Replace Method
    RegExpReplace = objRegExp.Replace(WhichString, ReplaceWith)

End Function

测试子看起来像这样:

Sub testRegex()
    Dim str As String
    str = "My 11/22@-@11:22@-@ test"

    MsgBox (str)

    Dim pattern As String
    pattern = "[0-9]{2}\/[0-9]{2}\@\-\@[0-9]{2}:[0-9]{2}\@\-\@"

    MsgBox (RegExpReplace(str, pattern, ""))
End Sub

结果:第一个消息框显示未更改的字符串

enter image description here

最后一个消息框显示删除了与正则表达式匹配的模式的字符串

enter image description here