Reputation: 173
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.
Upvotes: 0
Views: 1112
Reputation: 14580
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:
"sixty_six"
"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
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
Upvotes: 2