VB6.0 には Replace 関数が用意されているようだが、あいにく私は VB4.0 とVB5.0 しか持っていない。従って、文字列置換関数は自作しなければならない。
再帰処理で文字列置換を実現している。だってループさせるのが面倒なんだもん。大文字・小文字の区別などの処理は組み込んでいないシンプルバージョン。 '------------------------------------------------------------------- ' 関数名 : ReplaceText ' 機能 : 任意の文字列から文字列Aを文字列Bに置き換える ' 引数 : (in) srcText … 対象文字列 ' (in) tgtText … 被交換文字列 ' (in) chgText … 交換文字列 ' (in) SearchPos … 検索開始位置 ' 返り値 : 編集された文字列 '------------------------------------------------------------------- Public Function ReplaceText(ByVal srcText As String, _ ByVal tgtText As String, _ ByVal chgText As String, _ Optional ByVal SearchPos As Long = 1) As String Dim FoundPos As Long '被交換文字列検索 FoundPos = InStr(SearchPos, srcText, tgtText) '検索文字列が見つからなかったら、そのまま文字列を返して終了 If FoundPos = 0 Then ReplaceText = srcText Exit Function '検索文字列が見つかったら置換して再実行 Else '次回検索位置算出 SearchPos = FoundPos + Len(tgtText) '文字列置換 srcText = Mid$(srcText, 1, FoundPos - 1) & chgText & Mid$(srcText, SearchPos) '再実行(再帰) ReplaceText = ReplaceText(srcText, tgtText, chgText, SearchPos) End If End Functionループが面倒とは言ったものの、再帰関数を使うと処理速度がグッと落ちる。これはたまらない。ということで素直に普通の置換ロジックを作成した。こっちを使うのがよろしいでしょう。 '------------------------------------------------------------------- ' 関数名 : ReplaceText ' 機能 : 任意の文字列から文字列Aを文字列Bに置き換える ' 引数 : (in) srcText … 対象文字列 ' (in) tgtText … 被交換文字列 ' (in) chgText … 交換文字列 ' (in) SearchPos … 検索開始位置 ' 返り値 : 編集された文字列 '------------------------------------------------------------------- Public Function ReplaceText(ByVal srcText As String, _ ByVal tgtText As String, _ ByVal chgText As String, _ Optional ByVal SearchPos As Long = 1) As String Dim FoundPos As Long Do '被交換文字列検索 FoundPos = InStr(SearchPos, srcText, tgtText) '検索文字列が見つからなかったらループ終了 If FoundPos = 0 Then Exit Do '次回検索位置算出 SearchPos = FoundPos + Len(chgText) '文字列置換 srcText = Left$(srcText, FoundPos - 1) & chgText & Mid$(srcText, FoundPos + Len(tgtText)) Loop '編集した文字列を返す ReplaceText = srcText End Function 以下のデバッグ文で動作を確認してね Debug.Print ReplaceText("AABBCC", "B", "1") |