(Wordマクロ)テキストボックス内の文字を操作する
単一のword文書について、テキストボックス内の文字を操作します。
推奨シチュエーション
このマクロは、以下のシチュエーションでの使用に向いています。
- 本文は置換せず、テキストボックス内の文字のみを操作したい
テキストボックス内の文字操作例①
以下は、テキストボックス内の文字を10ptにする場合の例です。
Public Sub textbox_word() ''テキストボックス内の文字を10ptにする Dim x As Shape Dim s As Shape With ActiveDocument For Each x In .Shapes Select Case x.Type Case msoTextBox x.TextFrame.TextRange.Font.Size = 10 Case msoGroup For Each s In x.GroupItems If s.TextFrame.HasText = True Then s.TextFrame.TextRange.Font.Size = 10 Next s Case Else ' End Select Next x End With End Sub
<実行結果>
テキストボックス内の文字操作例②
以下は、テキストボックス内の最初の「2」を「4」に置換する例です。
Public Sub textbox_word() ''テキストボックス内の最初の「2」を「4」に置換する Dim x As Shape Dim s As Shape With ActiveDocument For Each x In .Shapes Select Case x.Type Case msoTextBox With x.TextFrame.TextRange If InStr(.Text, 2) <> 0 Then .Characters(InStr(.Text, 2)).Text = 4 End With Case msoGroup For Each s In x.GroupItems With s.TextFrame.TextRange If InStr(.Text, 2) <> 0 Then .Characters(InStr(.Text, 2)).Text = 4 End With Next s Case Else ' End Select Next x End With End Sub
<実行結果>
しかし、上のマクロでは、「2」が複数ある場合には対応できません。すべての「2」を置換したい場合は、以下のように「Do~Loop Until(While)」を使うなどして対応します。
テキストボックス内の文字操作例③
Public Sub textbox_word() ''テキストボックス内のすべての「2」を「4」に置換する Dim x As Shape Dim s As Shape Dim tmp As Long With ActiveDocument For Each x In .Shapes Select Case x.Type Case msoTextBox With x.TextFrame.TextRange Do If InStr(.Text, 2) <> 0 Then .Characters(InStr(.Text, 2)).Text = 4 Loop Until InStr(.Text, 2) = 0 End With Case msoGroup For Each s In x.GroupItems With s.TextFrame.TextRange Do If InStr(.Text, 2) <> 0 Then .Characters(InStr(.Text, 2)).Text = 4 Loop Until InStr(.Text, 2) = 0 End With Next s Case Else ' End Select Next x End With End Sub
最近のコメント