简体   繁体   中英

how to remove text after symbol or phrase in cell vba

I am trying to write a macro that would loop through a large set of rows (one particular column) and remove text if a specific word is found. Unfortunately I am not getting anywhere with that and was hoping that the community could help.

An example of the line would be

"One"Lorem ipsum dolor sit amet, consectetur adipiscing elit "sixty_six" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Desired outcome after macro would complete it's task would be:

"One"Lorem ipsum dolor sit amet, consectetur adipiscing elit

so everything starting with "sixty_six" and after would be deleted.

The code that I have so far is:

Sub removeData()

Dim i As Long
Dim lastRow As Long

lastRow = Cells(Rows.Count, "C").End(xlUp).Row

For i = 2 To lastRow

    If InStr(i.Value, "sixty_six") > 0 Then
        i.Value = Left(i.Value, InStr(i.Value, "sixty_six") - 1)
    End If

Next i


End Sub

The error that I am getting states "Invalid Qualifier" but not sure how I can fix it.

Thank you in advance for all your help.

First off, declare a worksheet so you can properly qualify your objects here. You are also looping through a invalid range - see proper way to loop through all rows on a column below (assuming your strings to be changed are in Column C )


Assuming your value "sixty_six" will either appear once or not at all , you can use Split to convert your string into two elements where:

  • The first element is everything before "sixty_six"
  • The second element is everything after (and including) "sixty_six"

If "sixty_six" does not appear in the string, the entire string will be held in the first element


Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")

Dim i As Long, lr As Long
Dim arr

lr = ws.Range("C" & ws.Rows.Count).End(xlUp).Row

For i = 2 To lr
    arr = Split(ws.Range("C" & i), """sixty_six""")

    ws.Range("C" & i) = arr(0)

    arr = ""
Next i

Alternative

You can avoid VBA all together by just using search and replace ( CTRL + F ) with a wildcard search of "sixty_six"* and a replacement of (a blank string).

Highlight target column and select Replace All .

在此处输入图片说明

@BigBen for calling out non-excel solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM