Excel VBA コード
Option Explicit
'Excel VBAで文字列の置き換え
'src: 元の文字
'fnd: 置き換え前の文字
'repl: 置き換え後の文字
Public Sub ExReplaceStr(src As String, fnd As String, repl As String)
Dim delpos As Long
Dim startpos As Long
Dim before As String
Dim after As String
'検索開始位置
startpos = 1
'開始の検索結果位置
delpos = InStr(startpos, src, fnd)
Do Until delpos = 0
'検索位置から前の文字
before = Left(src, delpos - 1)
'検索位置から後の文字
after = Right(src, (Len(src) - (delpos + Len(fnd) - 1)))
'置き換え後の文字
src = before & repl & after
'次の位置から繰り返す
startpos = Len(before) + Len(repl) + 1
delpos = InStr(startpos, src, fnd)
Loop
End Sub
Private Sub CommandButton1_Click()
Dim s1 As String
'置き換え前の文字
s1 = "あいうえおおまかせかきくけこ"
Range("B9") = s1
'文字列の置き換え
ExReplaceStr s1, "おまかせ", "食べる"
'置き換え結果の表示
Range("B10") = s1
End Sub
スポンサーリンク
Excel実行結果
コマンドボタンをクリックすると、B9に置き換え前の文字、B10に置き換え後の文字が表示されます。