Excel VBA-删除部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30024421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA- remove part of the string
提问by phani
I am trying to delete part of the string. For examplemystring="site, site text, sales "
我正在尝试删除部分字符串。例如mystring="site, site text, sales "
I want to remove 'site' from mystring. My required output is "site text, sales"
我想从 mystring 中删除“站点”。我需要的输出是“站点文本,销售”
I use this line of code :
我使用这行代码:
s1 = Replace(mystring, "site", "")
but i am getting "text, sales"
但我得到 "text, sales"
I am not sure how to do this and I'd really appreciate your help!
我不知道该怎么做,非常感谢您的帮助!
回答by Adrian
replace("site, site text, sales ","site, ","",1,1)
You can also send as a parameter the start position and then the number of times you want to replace... (the default is -1)
您还可以将开始位置作为参数发送,然后发送您要替换的次数...(默认为 -1)
回答by R3uK
There are a lot of different options here :
这里有很多不同的选择:
Just by adding the coma in the search stringto be replaced and use Trimto get rid of spaces :
只需在要替换的搜索字符串中添加昏迷并使用Trim以摆脱空格:
s1 = Trim(Replace(mystring, "site,", ""))
Specify the number of time you want the string to be replaced(first "1" is the start, the second for the number of replacements)
指定您希望字符串被替换的次数(第一个“1”是开始,第二个是替换次数)
s1 = Trim(Replace(mystring, "site,", "",1,1))
Or the hard/bad way, to decompose your string in two piecesafter the first occurence and then recombine to get result...
或者硬/坏的方式,在第一次出现后将你的字符串分解成两部分,然后重新组合以获得结果......
TempStart = Left(mystring, InStr(1, mystring, "site") + Len(mystring) + 1)
TempEnd = Replace(mystring, TempStart, "")
TempStart = Replace(TempStart, "site", "")
mystring = CStr(TempStart & TempEnd)
回答by R3uK
In my case I wanted to remove the part of the strings that was between "[" and "]". And the following code worked great.
就我而言,我想删除“[”和“]”之间的字符串部分。以下代码效果很好。
So With original string in column A (and solution in column B):
因此,使用 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
回答by Anarach
You can also user VB's MID function like this:
您还可以像这样使用 VB 的 MID 函数:
Mystring=Mid(myString, 6)
output will be "site text, sales"
输出将是“网站文字,销售”
Just specify the number of characters you want to be removed in the numberpart.
只需在数字部分指定要删除的字符数即可。

