[英]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. “One”Lorem ipsum dolor sat amet,consectetur adipiscing 精英“sixty_six”sed do eiusmod tempor incididunt ut laboure et dolore magna aliqua。
Desired outcome after macro would complete it's task would be:宏完成后的预期结果是:
"One"Lorem ipsum dolor sit amet, consectetur adipiscing elit “One”Lorem ipsum dolor sat amet, consectetur adipiscing elit
so everything starting with "sixty_six" and after would be deleted.所以所有以“sixty_six”开头的内容都将被删除。
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
)您还遍历了一个无效范围 - 请参阅正确的方法来遍历下面一列上的所有行(假设要更改的字符串在
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"
将出现一次或根本不出现,您可以使用Split
将您的字符串转换为两个元素,其中:
"sixty_six"
"sixty_six"
之前的所有内容"sixty_six"
"sixty_six"
If "sixty_six" does not appear in the string, the entire string will be held in the first element如果字符串中没有出现“sixty_six”,则整个字符串将保存在第一个元素中
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您可以通过使用
"sixty_six"*
的通配符搜索和替换( CTRL + F )来一起避免 VBA (a blank string).
(空字符串)。
Highlight target column and select Replace All
.突出显示目标列并选择
Replace All
。
@BigBen for calling out non-excel solution @BigBen 用于调用非 Excel 解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.