1
1

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 3 years have passed since last update.

VBAで図形内の文字を置換する

Posted at

図形(オートシェイプ)内のテキストを置換するマクロです。
検索対象の文字列をB1セルに入力し、置換後の文字列をB2セルに入力し、マクロを実行すると、図形内の文字列が変換されます。

image.png

image.png

'Option Explicitステートメントは、モジュールの中で使用すると
'そのモジュールでは変数を宣言しないとマクロが動かなくなる。
'Option Explicitを使うことで、変数入力ミス時にどこの変数が入力ミスしているか黄色ハイライトで教えてくれる
Option Explicit

Sub TextReplacementForShapes()

 Dim TargetWorkSheet As Worksheet '置換対象のシート
 Dim TargetShape As Shape '置換対象の図形
 Dim TargetText As String '置換対象のテキスト

 Dim SearchText As String '検索するテキスト
 SearchText = Range("B1")

 Dim ReplaceText As String '置換後のテキスト
 ReplaceText = Range("B2")
 
 Set TargetWorkSheet = Application.ActiveSheet 'アクティブシートを置換対象シートの変数に格納

 '図形のテキストを置換
 'For Eachでブック内の全てのオブジェクトを対象に処理する
 'For Each構文
 ' For Each オブジェクト変数 In オブジェクト
 ' 繰り返し処理
 ' Next オブジェクト変数

 For Each TargetShape In TargetWorkSheet.Shapes
  If TargetShape.TextFrame2.HasText Then 'テキストがある場合、以下の処理を実行
   TargetText = TargetShape.TextFrame.Characters.Text
   TargetShape.TextFrame.Characters.Text = Replace(TargetText, SearchText, ReplaceText) 'Replace(置換対象の文字列, 検索する文字列, 置換後の文字列)
  End If
 Next TargetShape

 Set TargetWorkSheet = Nothing

End Sub
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?