VBA - 替換



Replace 函式用特定字串替換特定部分的字串,次數可以指定。

語法

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

引數說明

  • String − 必需引數。需要搜尋以進行替換的輸入字串。

  • Find − 必需引數。將被替換的字串部分。

  • Replacewith − 必需引數。替換字串,它將針對 find 引數替換。

  • 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
vba_strings.htm
廣告
© . All rights reserved.