[英]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.