[英]Excel VBA- remove part of the string
我想刪除部分字符串。 例如
mystring="site, site text, sales "
我想從mystring中刪除' site '。 我要求的輸出是“網站文字,銷售”
我用這行代碼:
s1 = Replace(mystring, "site", "")
但我得到"text, sales"
我不知道該怎么做,我真的很感謝你的幫助!
replace("site, site text, sales ","site, ","",1,1)
您還可以將起始位置作為參數發送,然后發送要替換的次數...(默認值為-1)
這里有很多不同的選擇:
只需在要替換的搜索字符串中添加昏迷,然后使用Trim
去除空格:
s1 = Trim(Replace(mystring, "site,", ""))
指定要替換字符串的時間 (第一個“1”是開頭,第二個是替換次數)
s1 = Trim(Replace(mystring, "site,", "",1,1))
或者是硬/壞的方式,在第一次出現之后將你的字符串分解成兩部分 ,然后重新組合以獲得結果......
TempStart = Left(mystring, InStr(1, mystring, "site") + Len(mystring) + 1)
TempEnd = Replace(mystring, TempStart, "")
TempStart = Replace(TempStart, "site", "")
mystring = CStr(TempStart & TempEnd)
在我的情況下,我想刪除“[”和“]”之間的字符串部分。 以下代碼運行良好。
所以使用A列中的原始字符串(以及B列中的解決方案):
Sub remove_in_string()
Dim i, lrowA, remChar As Long
Dim mString As String
lrowA = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lrowA
mString = Cells(i, 1).Value
If InStr(mString, "[") > 0 Then
remChar = InStr(mString, "]") - InStr(mString, "[") + 1
Cells(i, 2).Value = Left(mString, Len(mString) - remChar)
ElseIf InStr(mString, "[") = 0 Then
Cells(i, 2).Value = Cells(i, 1).Value
End If
Next
End Sub
您也可以像這樣使用VB的MID函數:
Mystring=Mid(myString, 6)
輸出將是“網站文字,銷售”
只需在數字部分中指定要刪除的字符數 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.