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.

Excelファイルのテキストを書式やフォントを維持したまま置換する方法

Last updated at Posted at 2023-04-19

はじめに

Excelでは置換をしたときにセルの一文字目の書式と同じ書式になってしまうという特性があります。
今回はセル内の文字の書式やフォントを維持したまま置換する方法を紹介します。
引用元:https://ja.extendoffice.com/documents/excel/3760-excel-find-and-replace-preserve-formatting.html#a1

今回やりたいこと

Excelの仕様と今回やりたいことをまとめると図のようになります。
image.png

実際のやり方

ボタンの作成

まずボタンを作成し、ボタンをクリックしたときにマクロが実行されるようにします。ボタンを作成するには、開発ツールバーの[フォームコントロール]にある[ボタン]を選択し、ワークシート上にボタンを描画します。
image.png

このマクロをボタンに割り当てるには、ボタンを右クリックし、[マクロの割り当て]を選択し、ソースコードを記入したプロジェクトシートまたはモジュールを選択しOKを押下します。
image.png
image.png

コード例

マクロに導入するコードはこちらです。

CharactersReplace
Sub CharactersReplace(rng As Range, findText As String, ReplaceText As String, Optional MatchCase As Boolean = False)
  'Update20230419
    Dim I As Long
    Dim xLenFind As Long
    Dim xLenRep As Long
    Dim K As Long
    Dim xValue As String
    Dim M As Long
    Dim xCell As Range
    xLenFind = Len(findText)
    xLenRep = Len(ReplaceText)
    If Not MatchCase Then M = 1
    For Each xCell In rng
        If VarType(xCell) = vbString Then
            xValue = xCell.Value
            K = 0
            For I = 1 To Len(xValue)
              If StrComp(Mid$(xValue, I, xLenFind), findText, M) = 0 Then
                xCell.Characters(I + K, xLenFind).Insert ReplaceText
                K = K + xLenRep - xLenFind
              End If
            Next
        End If
    Next
End Sub

Sub Test_CharactersReplace()
    Dim xRg As Range
    Dim xTxt As String
    Dim xCell As Range
    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      xTxt = ActiveWindow.RangeSelection.AddressLocal
    Else
      xTxt = ActiveSheet.UsedRange.AddressLocal
    End If
    Set xRg = Application.InputBox("範囲を選択してください:", "書式を保持したまま置換する", xTxt, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    Call CharactersReplace(xRg, "たちつてと", "なにぬねの", True)
End Sub

各行の説明は引用元を参照し、正確に理解できていないため割愛します。
使い方は至ってシンプル。
下から二行目の”たちつてと”が置換対象文字列。”なにぬねの”が置換後の文字列となりますので、実行前に書き換えていただければ完了です。

Call CharactersReplace(xRg, "たちつてと", "なにぬねの", True)

導入結果

実際に動かしてみます。
”たちつてと”が書式とフォントを維持したまま”なにぬねの”に置換されれば成功です。

ボタンを押下してB27を範囲選択
image.png

image.png

”たちつてと”の書式とフォントを維持したまま”なにぬねの”に置換することが出来ました。
image.png

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?