VBA - Replace



The Replace function replaces a specified part of a string with a specific string, a specified number of times.

Syntax

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

Parameter Description

  • String − A required parameter. The Input String which is to be searched for replacing.

  • Find − A required parameter. The part of the string that will be replaced.

  • Replacewith − A required parameter. The replacement string, which would be replaced against the find parameter.

  • Start − An optional parameter. Specifies the start position from where the string has to be searched and replaced. Default value is 1.

  • Count − An optional parameter. Specifies the number of times the replacement has to be performed.

  • Compare − An optional parameter. Specifies the comparison method to be used. Default value is 0.

    • 0 = vbBinaryCompare - Performs a binary comparison

    • 1 = vbTextCompare - Performs a Textual comparison

Example

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

When you execute the above function, it produces the following output.

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
Advertisements