![](/img/trans.png)
[英]How to remove characters in a cell after the first blank space using VBA?
[英]how to remove text after symbol or phrase in cell vba
我正在嘗試編寫一個宏,該宏將遍歷大量行(一個特定列)並在找到特定單詞時刪除文本。 不幸的是,我對此一無所知,並希望社區可以提供幫助。
該行的一個例子是
“One”Lorem ipsum dolor sat amet,consectetur adipiscing 精英“sixty_six”sed do eiusmod tempor incididunt ut laboure et dolore magna aliqua。
宏完成后的預期結果是:
“One”Lorem ipsum dolor sat amet, consectetur adipiscing elit
所以所有以“sixty_six”開頭的內容都將被刪除。
我到目前為止的代碼是:
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
我收到的錯誤指出“無效的限定符”,但不確定如何修復它。
在此先感謝您的幫助。
首先,聲明一個工作表,以便您可以在此處正確地限定您的對象。 您還遍歷了一個無效范圍 - 請參閱正確的方法來遍歷下面一列上的所有行(假設要更改的字符串在Column C
)
假設您的值"sixty_six"
將出現一次或根本不出現,您可以使用Split
將您的字符串轉換為兩個元素,其中:
"sixty_six"
之前的所有內容"sixty_six"
如果字符串中沒有出現“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
您可以通過使用"sixty_six"*
的通配符搜索和替換( CTRL + F )來一起避免 VBA (空字符串)。
突出顯示目標列並選擇Replace All
。
@BigBen 用於調用非 Excel 解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.