![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
VBAで
・変数の設定値(文字列)を置換
できます!
![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
VBA関数である
・Replace関数
により実現できます!
VBAコード
ここでは例として
・文字列「りんごは美味しい!」の
・「りんご」を「バナナ」へ置換
します。
Option Explicit
Sub sample()
Dim beforeStr As String
Dim srcStr As String
Dim destStr As String
Dim afterStr As String
'置換対象の文字列を設定
beforeStr = "りんごは美味しい!"
'置換前の文字列を設定
srcStr = "りんご"
'置換後の文字列を設定
destStr = "バナナ"
'置換する
afterStr = Replace(expression:=beforeStr, _
Find:=srcStr, _
Replace:=destStr, _
compare:=vbTextCompare)
'置換結果を確認
MsgBox (afterStr)
End Sub
実行結果
変数の設定値(文字列)を置換できました。
※文字列「りんごは美味しい!」の「りんご」を「バナナ」へ置換できました。
![実行結果](https://excel-vba.work/wp-content/uploads/2022/02/vba_func_replace_001.png)
参考①
シート上の文字列を置換することもできます。
詳細は以下の記事をご確認ください。
参考②
上記のVBAコードで使用している以下の詳細は、公式サイトをご確認ください。
●Replace関数