0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VBA_任意文字の間の文字を抜き出す(複数箇所可能)

0
Posted at

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!!!!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?