hiko-blog

VBA業務改善

MENU

特定の文字変換

Sub HighlightAndConvertText()
    Dim ws As Worksheet
    Dim rng As Range
    Dim cell As Range
    Dim hasTarget As Boolean
    Dim convertedCount As Long
    
    ' 対象のシートを指定
    Set ws = ThisWorkbook.Sheets("Sheet1")  ' シート名を適切に変更
    
    ' 対象の範囲を指定(C列に限定)
    Set rng = ws.Range("C1:C" & ws.Cells(ws.Rows.Count, "C").End(xlUp).Row)

    ' 検索してセルを黄色にハイライト
    For Each cell In rng
        If InStr(1, cell.Value, "変換文字1") > 0 Or InStr(1, cell.Value, "変換文字2") > 0 Then
            cell.Interior.Color = RGB(255, 255, 0)  ' 黄色
            hasTarget = True
            convertedCount = convertedCount + 1
        End If
    Next cell

    ' 対象セルがない場合、メッセージを表示して終了
    If Not hasTarget Then
        MsgBox "対象セルはC列にありませんでした。", vbInformation, "処理終了"
        Exit Sub
    End If

    ' ユーザーに確認メッセージを表示
    MsgBox "対象セルはC列に" & convertedCount & "件(黄色箇所)。" & vbLf & "OKをクリックすると変換します。", vbInformation + vbOKOnly, "変換の確認"

    ' 黄色にハイライトされたセルを変換
    For Each cell In rng
        If cell.Interior.Color = RGB(255, 255, 0) Then
            cell.Value = Replace(cell.Value, "変換文字1", "変換後文字1")
             cell.Value = Replace(cell.Value, "変換文字2", "変換後文字2")
            cell.Interior.ColorIndex = xlNone  ' ハイライトを解除
        End If
    Next cell

    ' 変換完了メッセージを表示
    MsgBox "変換が完了。", vbInformation, "変換完了"
End Sub