位置:首页 » 文章/教程分享 » VBA 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