Vba-replace-function
提供:Dev Guides
VBA-交換
Replace関数は、指定された回数、文字列の指定された部分を特定の文字列に置き換えます。
構文
Replace(string,find,replacewith[,start[,count[,compare]]])
パラメータ説明
- String -必須パラメーター。 置換のために検索される入力文字列。
- 検索-必須パラメーター。 置換される文字列の部分。
- Replacewith -必須パラメーター。 検索パラメーターに対して置換される置換文字列。
- 開始-オプションのパラメーター。 文字列を検索して置換する開始位置を指定します。 デフォルト値は1です。
- Count -オプションのパラメーター。 置換を実行する必要がある回数を指定します。
- 比較-オプションのパラメーター。 使用する比較方法を指定します。 デフォルト値は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