| 文字列中の特定文字列を置き換えるユーザー定義関数 |
|
対象バージョン : 97
最終更新日 : 1999/09/12 (オリジナル作成日 : 1998/12/10)
概 要
与えられた文字列の中から、文字列を検索し、その文字列があれば指定した文字列に置き換えるユーザー定義関数です。
【例】
| 元の文字列 | "ABCDEFGHABCDEFGH" |
| 検索する文字列 | "DEF" |
| 置換する文字列 | "YZ" |
| 結果 | "ABCYZGHABCYZGH" |
構 文
ReplaceString(Source, Before, After [,Compare])
解 説
ReplaceString 関数の戻り値は文字列型 (String)です。
ReplaceString 関数では次の引数を使用します。
| 引 数 | 内 容 | ||||||
|---|---|---|---|---|---|---|---|
| Source | 変換する元の文字列を文字列式で指定します。 Null の場合、この関数は長さ 0 の文字列を返します。 |
||||||
| Before | 検索する文字列を文字列式で指定します。 Null の場合、この関数は長さ 0 の文字列を返します。 |
||||||
| After | Before
で指定した文字列があった場合に置き換える文字列を文字列式で指定します。 長さ 0 の文字列も可能です。 Null の場合、長さ 0 の文字列とみなします。 |
||||||
| Compare | Source
を検索する際の比較方法を指定します。
この引数は省略可能です。 既定値は vbDatabaseCompare です。 |
ユーザー定義関数
Public Function ReplaceString(argSource As Variant, argBefore As Variant, _
argAfter As Variant, Optional argCompare) As String
Dim strString As String
Dim lngPos As Long
Dim lngBeforeLen As Long
Dim lngAfterLen As Long
Dim strAfter As String
Dim intCompare As Integer
If IsNull(argSource) Or argSource = "" Then Exit Function
If IsNull(argBefore) Or argBefore = "" Then Exit Function
If IsNull(argAfter) Then
strAfter = ""
Else
strAfter = argAfter
End If
If IsMissing(argCompare) Then
intCompare = vbDatabaseCompare
Else
intCompare = argCompare
End If
lngBeforeLen = Len(argBefore)
lngAfterLen = Len(strAfter)
strString = argSource
lngPos = InStr(1, strString, argBefore, intCompare)
Do While lngPos > 0
strString = Left(strString, lngPos - 1) & strAfter & _
Mid(strString, lngPos + lngBeforeLen)
lngPos = InStr(lngPos + lngAfterLen, strString, argBefore, intCompare)
Loop
ReplaceString = strString
End Function
使 用 例
ReplaceString("ABCDabcd", "AB", "ZZ") → "ZZCDZZcd"
ReplaceString("ABCDabcd", "AB", "ZZ", vbBinaryCompare) → "ZZCDabcd"
補 足
改定履歴