2015-05-04 1274 views
3

我想刪除部分字符串。例如
mystring="site, site text, sales "Excel VBA-刪除部分字符串

我想刪除了mystring '網站'。我需要輸出「網站的文字,銷售」

我使用這行代碼:

s1 = Replace(mystring, "site", "") 

但我正在逐漸"text, sales"

我不知道如何做到這一點。我」 d非常感謝你的幫助!

回答

6
replace("site, site text, sales ","site, ","",1,1) 

您還可以發送作爲參數的起始位置,然後你想更換的次數。(默認值爲-1)

+0

爲了記錄在案,遵循更換的參數:'公共功能替換( BYVAL表達作爲字符串, BYVAL找到,因爲字符串, ByVal替換爲字符串, 可選ByVal作爲整數開始= 1, 可選ByVal作爲整數= -1, 可選ByVal比較CompareMethod = CompareMethod.Binary )As String' –

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) 
1

您還可以用戶VB的MID功能是這樣的:

Mystring=Mid(myString, 6) 

輸出將是「網站的文字,銷售」

只要指定在部分被刪除你想要的字符數。

0

在我的情況下,我想刪除「[」和「]」之間的部分字符串。下面的代碼工作得很好。

因此,與在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