2017-03-03 106 views
0

編輯:使用按鈕替換字符串vba

我更關注PHP,我剛開始學習VBA。 這是我爲按鈕製作的代碼。

Private Sub btnConvert_Click() 

Dim a As String 
Dim b As String 
Dim c As String 
Dim d As String 
Dim e As String 
Dim f As String 


a = "a" 
b = "b" 
c = "c" 
d = "d" 
e = "e" 
f = "f" 
Columns("B").Replace what:=a, replacement:=b, lookat:=xlPart, MatchCase:=False 
Columns("B").Replace what:=c, replacement:=d, lookat:=xlPart, MatchCase:=False 
Columns("B").Replace what:=e, replacement:=f, lookat:=xlPart, MatchCase:=False 
End Sub 

現在,我的問題是:在 代碼就像上面,它發生的「B」將與「一」來代替。 但現在我也想刪除一部分字符串。

例如字符串是:

a(hey)/(qworty); 
c(yow)/(asdf); 
e(wow)/(zxcv_786); 

當我點擊按鈕上的文本應該被替換爲:

b(hey); 
c(yow); 
e(wow); 

希望你明白。 謝謝。

+1

'列( 「B」)更換什麼:= 「/(qworty)」,替換:= 「」,LOOKAT:= xlPart,MatchCase:= FALSE' –

+0

我改變這些實施例。抱歉。 – akamariaclaraaa

回答

2

你可以試試這個:

Private Sub btnConvert_Click() 

    Dim a As String 
    Dim b As String 
    Dim c As String 
    Dim d As String 
    Dim e As String 
    Dim f As String 


    a = "a" 
    b = "b" 
    c = "c" 
    d = "d" 
    e = "e" 
    f = "f" 

    With columns("B") 
     .Replace what:="/*;", Replacement:=";", lookat:=xlPart, MatchCase:=False 
     .Replace what:=a & "(", Replacement:=b & "(", lookat:=xlPart, MatchCase:=False 
     .Replace what:=c & "(", Replacement:=d & "(", lookat:=xlPart, MatchCase:=False 
     .Replace what:=e & "(", Replacement:=f & "(", lookat:=xlPart, MatchCase:=False 
    End With 
End Sub 
+0

@akamariaclaraaa,你通過它了嗎? – user3598756

+0

@akamariaclaraaa,有沒有機會從你那裏得到反饋? – user3598756

0

雖然你可以運行一個查找和使用正則表達式替換(有很多的例子在本網站),你也可以循環在你的範圍,建立並通過分割陣列字符串放在「/」處,並將數組的第一個元素寫回單元格。

Private Sub btnConvert_Click() 
Dim c As Range 
Dim arr() As String 

    'Loop Column B. Change This If It Doesn't Exactly Meet Your Requirements 
    For Each c In Range("B:B") 
     'Exit When We Get To An Empty Cell. Again This May Need To Be Changed Depending On Requirements 
     If Len(c) = 0 Then Exit For 
     'Create An Array 
     arr() = Split(c, "/") 
     'Write The First Element Back 
     c = arr(0) 
    Next c 

End Sub