LoginSignup
2
1

More than 3 years have passed since last update.

Excelでテキストボックス内の文字列を置換するマクロ

Last updated at Posted at 2019-09-30

現状Excelではテキストボックス内の文字列を置換する機能が備わっていないので、ネットの記事を参考にしてユーザーフォームを使うマクロを作ってみた。

2019/10/14 ユーザーフォーム内の記述をMeキーワードを使用するよう修正しました。

ユーザーフォーム

こんな感じでユーザーフォームを作る。「置換」ボタンがCommandBotton1、「閉じる」ボタンがCommandBotton2。
image.png

コード

コードはこんな感じ。

Private Sub CommandButton1_Click()
    Dim xWst As Worksheet
    Dim shps As Shape
    Dim xFindStrs As String
    Dim xReplaces As String
    Dim xValues As String

    xFindStrs = Me.TextBox1.Text
    xReplaces = Me.TextBox2.Text
    Set xWst = Application.ActiveSheet
    On Error Resume Next
    For Each shps In xWst.Shapes
        xValues = shps.TextFrame.Characters.Text
        shps.TextFrame.Characters.Text = VBA.Replace(xValues, xFindStrs, xReplaces, 1)
    Next
    Unload Me
End Sub

Private Sub CommandButton2_Click()
    Unload Me
End Sub

ユーザーフォームの呼び出し

標準モジュールでこう。あとはこいつをキーボードショートカットで呼び出せるようにする。

Sub TextBoxReplace()
    UserForm1.Show
End Sub
2
1
2

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
2
1