Excelの任意セルから、任意文字と文字の間を抽出するマクロだよん。
複数箇所あっても対応しているよん。
イメージ:
同一セル内に
《あああ》いいい《ううう》えええ《おお
お》
と改行があった際に、
・あああ
・ううう
・おお
お
と表示したい!
(改行は改行として認識したい)
まずは、完成形サンプルコード
' 《》内のテキストを抽出
Function ExtractTextBetweenBrackets(inputText As String) As String
Dim result As String ' 結果文字列
Dim startPos As Long ' 《の位置
Dim endPos As Long ' 》の位置
Dim currentPos As Long ' 現在の検索位置
Dim extractedPart As String ' 抽出されたテキスト
' Null や空文字の場合の処理
If inputText = "" Or IsNull(inputText) Then
ExtractTextBetweenBrackets = ""
Exit Function
End If
currentPos = 1
result = ""
' 《》のペアを順次検索
Do
' 《の位置を検索
startPos = InStr(currentPos, inputText, "《")
If startPos = 0 Then Exit Do
' 》の位置を検索
endPos = InStr(startPos + 1, inputText, "》")
If endPos = 0 Then Exit Do
' 《》内のテキストを抽出
extractedPart = Mid(inputText, startPos + 1, endPos - startPos - 1)
' 結果に追加
If result <> "" Then
result = result & vbCrLf
End If
result = result & "・" & extractedPart
' 次の検索位置
currentPos = endPos + 1
Loop
ExtractTextBetweenBrackets = result
End Function
関数にしているから、この関数を下記のように呼び出して、引数に対象セルの値を渡してね!
Dim extractedText As String
extractedText = ExtractTextBetweenBrackets(cellValue)
イメージは、、、
' 各行を処理
For i = startRow To lastRow
' 値を取得
cellValue = ""
On Error Resume Next
If Not IsEmpty(ws.Cells(i, processColumn).Value) And Not IsNull(ws.Cells(i, processColumn).Value) Then
cellValue = CStr(ws.Cells(i, processColumn).Value)
cellValue = Replace(cellValue, vbLf, vbCrLf)
cellValue = Replace(cellValue, vbCr & vbCrLf, vbCrLf)
End If
On Error GoTo ErrorHandler
' 《》内のテキストを抽出
extractedText = ExtractTextBetweenBrackets(cellValue)
みたいなイメージかな~!
文字の開始、終了位置を検索して、その間の文字数をつないでいるよん。
複数ある場合、”・”を使用して改行して出力するよ!
CSVとかデータ移行とかいろいろ応用が効くよね!
さすがVBA!!!!!