选择和删除字符

时间:2014-04-04 12:49:41

标签: vba excel-vba excel

我试图删除删除用户输入的字符串以及此字符串后面的后16个字符...当我删除我输入的字符串时,它正在工作,但当我要求删除其他16个字符时,它会停止工作。有人可以帮助我吗?

文件是:

04_03(+16个字符)文本04_03(+ 16个字符)

04_03(+16个字符)文本04_03(+ 16个字符)文本04_03(+ 16个字符)

text 04_03(+ 16characters)

用户输入: strSearch = 04_03

我想在此字符串之后删除字符串04_03以及接下来的16个字符,以及它们来自文件的字符。

最终文件应为:

文本

文字文字

文本

Global strSearch As String
Global strLenght As Double

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

strSearch = InputBox("How starts the text that you would like to remove?", "Character's Search")
If strSearch = "" Then Exit Sub

End Sub

Sub RemoveCharacters()

Dim pattern As String
Dim str As String
Dim u As String

With Sheets("Sheet1")
.Select

Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

    For Lrow = 1 To Lastrow Step 1

        str = Cells(Lrow, 1).Value
        pattern = strSearch + " [\w \W \s] {16}"
        Cells(Lrow, 1).Value = RegExpReplace(str, pattern, "")

    Next Lrow

End With

End Sub

1 个答案:

答案 0 :(得分:0)

这是你在尝试的吗?

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, pos As Long, i As Long, n As Long
    Dim strToRepl As String, strSearch As String

    strSearch = InputBox("How does the text start that you would like to remove?", "Character's Search")
    If strSearch = "" Then Exit Sub

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            pos = InStr(1, .Range("A" & i).Value, strSearch, vbTextCompare)

            If pos > 0 Then
                n = Len(.Range("A" & i).Value) - pos

                If Not Len(strSearch) + 16 > n Then
                    strToRepl = Mid(.Range("A" & i).Value, pos, Len(strSearch) + 16)
                    .Range("A" & i).Value = Replace(.Range("A" & i).Value, strToRepl, "")
                End If
            End If
        Next i
    End With
End Sub

<强>截图

enter image description here