LoginSignup
1
0

More than 3 years have passed since last update.

Excel for Macでシェイプテキスト置換ボタンを作る

Last updated at Posted at 2020-03-19

業務の都合上、自分だけMacユーザーでほかの全員がWindowsとエクセルで画面設計書を作っているという状況が稀によくあります。Mac版のエクセルでワイヤーフレーム的なのを書くのは挙動が重いので苦手ですが、協業する上では仕方がない場合もあります。

さて、画面の絵の上によくシェイプテキストを乗っけて注釈やIDを付けることがありますが、シェイプテキストは標準の検索置換機能には対応していません。これを実現するにはVBAが必要ですが、ありがたいことに既にQiitaに記事がありました。

上記の記事を参考にMac版のエクセルでツールバーから使えるシェイプテキスト置換機能を作ってみました。

使い方

オリジナルのコードはセル内で呼び出す関数でしたが、これをリボンから呼び出す機能に変更しています。
1つ〜複数のシェイプが選択中である場合は、そのシェイプだけを対象に置換。
シェイプ未選択の場合はシート内の全シェイプを対象に置換します。

  1. ツールバーボタンを押すと入力欄が出るので、カンマ区切りで検索文字,置換文字の形式で入力

    image.png

    • 検索・置換文字自体に半角カンマが含まれる場合は\,でエスケープ
  2. キャンセルを押したり、入力文字にカンマが無かったりするとメッセージが出て終了

    image.png

  3. 問題なければシェイプテキストが置換されます

    • 選択中のシェイプがない場合: シート内のすべてのシェイプが置換の対象になります
    • 選択中のシェイプがある場合: 選択されているシェイプだけが置換の対象になります image.png

コード

Sub ReplaceShapeText()

  Dim sh As Shape
  Dim userInput As String
  Dim findStr As String
  Dim repStr As String
  Dim commaEscape As String
  Dim commaEscapePtn As String

  commaEscape = "\,"
  commaEscapePtn = "%%COMMA%%"

  userInput = Application.InputBox("Please input search text and replace text with a comma. Use /, to escape comma.  Example) find,replace")
  userInput = Replace(userInput, commaEscape, commaEscapePtn)

  If Len(userInput) < 3 Or InStr(userInput, ",") = 0 Then
    MsgBox ("Your input does not fill the requirement. Quit the execution.")
    Exit Sub
  End If

  findStr = Split(userInput, ",")(0)
  findStr = Replace(findStr, commaEscapePtn, ",")

  repStr = Split(userInput, ",")(1)
  repStr = Replace(repStr, commaEscapePtn, ",")

  If TypeName(Application.Selection) <> "Nothing" And TypeName(Application.Selection) <> "Range" Then

    For Each sh In Selection.ShapeRange
      If sh.TextFrame2.HasText = msoTrue And sh.Type <> msoGroup Then
        Call sh.TextFrame2.TextRange.Replace(findStr, repStr)
      End If
    Next

  Else

    For Each sh In ActiveSheet.Shapes
      If sh.TextFrame2.HasText = msoTrue And sh.Type <> msoGroup Then
        Call sh.TextFrame2.TextRange.Replace(findStr, repStr)
      End If
    Next

 End If

End Sub

リボンへの登録方法

最初VBAの使い方が全く分からなかったので詳しめに記載。

  1. ファイルを全て閉じる
  2. 適当な新規ブックを作成する
  3. メニューの「ツール > マクロ」から、Visual Basic Editorを開く
  4. 左のツリーから"This Workbook"をダブルクリックしてコードをペースト image.png
  5. ブックを Excel Add-in 形式で保存
    image.png
  6. メニューの「ツール > Excelアドイン…」を選択(「挿入 > アドイン」ではないので注意)
  7. 先程保存した拡張子が.xlamのファイルを一覧に登録し、チェックボックスを付ける
    image.png
  8. メニューの「Excel > 環境設定」を開き、リボンのカスタマイズ画面へ移動する
  9. 左側のプルダウンを「マクロ」に変更し、適当なリボンにボタンを追加する image.png

感想・ハマったところ

仕様です

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