前回の記事「【コード】文字列を横方向に移動するWordマクロ(その2)」の横方向の動きを縦方向に応用しました。
<目次>
このマクロでできること
選択されている文字列を文字列を上方向と下方向に移動します。
文字列が選択されていない状態で実行すると、カーソル位置の単語を一つ選択します。
実行前
実行後
マクロの解説
前回の記事「【コード】文字列を横方向に移動するWordマクロ(その2)」と同じ仕組みで動いています。
今回は25行目の記述が少し異なります。カーソルの移動が上下に行をまたいだ動きになっているので、MoveUpメソッド を使っています。
マクロ1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | Sub 文字列移動_上() Dim myRange As Range '元の文字列 Dim blnPaste As Boolean '貼り付け時の自動調整 Set myRange = Selection.Range '単語の選択 If Selection.Type = wdSelectionIP Then Selection.Expand wdWord Exit Sub End If '貼り付け時の自動調整(設定変更) blnPaste = Options.PasteSmartCutPaste Options.PasteSmartCutPaste = False '移動先の設定 With Selection '選択の解除 .Collapse wdCollapseStart '上方向にカーソルを移動 If .MoveUp(unit:=wdLine, Count:=1) > 0 Then 'コピペ(文字書式も貼り付けます) .FormattedText = myRange.FormattedText '移動先の文字列を選択 . End = . End + Len(myRange.Text) '元の文字列を削除 myRange.Delete Else 'カーソル位置を元の場所に戻す myRange. Select End If End With '貼り付け時の自動調整(設定復帰) Options.PasteSmartCutPaste = blnPaste 'Rangeオブジェクトの解放 Set myRange = Nothing End Sub |
マクロ2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | Sub 文字列移動_下() Dim myRange As Range '元の文字列 Dim blnPaste As Boolean '貼り付け時の自動調整 Set myRange = Selection.Range '単語の選択 If Selection.Type = wdSelectionIP Then Selection.Expand wdWord Exit Sub End If '貼り付け時の自動調整(設定変更) blnPaste = Options.PasteSmartCutPaste Options.PasteSmartCutPaste = False '移動先の設定 With Selection '選択の解除 .Collapse wdCollapseEnd '上方向にカーソルを移動 If .MoveDown(unit:=wdLine, Count:=1) > 0 Then 'コピペ(文字書式も貼り付けます) .FormattedText = myRange.FormattedText '移動先の文字列を選択 . End = . End + Len(myRange.Text) '元の文字列を削除 myRange.Delete Else 'カーソル位置を元の場所に戻す myRange. Select End If End With '貼り付け時の自動調整(設定復帰) Options.PasteSmartCutPaste = blnPaste 'Rangeオブジェクトの解放 Set myRange = Nothing End Sub |