VBA Replace函數

Replace

Replace函數替換字符串的指定部分與特定字符串指定次數。

語法 :

Replace(string,find,replacewith[,start[,count[,compare]]])

  • string, 必需的參數。要搜索替換輸入字符串。

  • find, 必需的參數。字符串的一部分將被替換。

  • replacewith, 必需的參數。替換串,這將被替換針對查找的參數。

  • start, 一個可選的參數。指定從其中所述串具有要被搜索和替換的開始位置。默認值是1。

  • count, 一個可選的參數。指定次數的置換設有要執行的次數。

  • compare, 一個可選的參數。指定要使用的比較方法。默認值爲0。

    • 0 = vbBinaryCompare - 執行二進制比較

    • 1 = vbTextCompare - 執行文本比較

示例 :

Private Sub Constant_demo_Click() Dim var as Variant var="This is VBScript Programming" 'VBScript to be replaced by MS VBScript
msgbox("Line 1: " & Replace(var,"VBScript","MS VBScript"))

'VB to be replaced by vb
msgbox("Line 2: " & Replace(var,"VB","vb")) ''is' replaced by ##
msgbox("Line 3: " & Replace(var,"is","##"))

''is' replaced by ## ignores the characters before the first occurence msgbox("Line 4: " & Replace(var,"is","##",5)) ''s' is replaced by ## for the next 2 occurences.
msgbox("Line 5: " & Replace(var,"s","##",1,2))

''r' is replaced by ## for all occurences textual comparison. msgbox("Line 6: " & Replace(var,"r","##",1,-1,1)) ''t' is replaced by ## for all occurences Binary comparison
msgbox("Line 7: " & Replace(var,"t","##",1,-1,0))

End Sub

當執行函數輸出如下所示:

Line 1: This is MS VBScript Programming Line 2: This is vbScript Programming Line 3: Th## ## VBScript Programming Line 4: ## VBScript Programming Line 5: Thi## i## VBScript Programming Line 6: This is VBSc##ipt P##og##amming Line 7: This is VBScrip## Programming