0
0

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.

Word VBAのグループ化が時々失敗する

Last updated at Posted at 2021-01-23

事象

C#で NetOffice を使ってWordの中のオートシェイプをグループ化する要件があった。その際に時々成功するが、時々失敗するという事象に悩まされたので、ここにメモしておく。

具体的には以下のようなコードで問題が発生した。

private void Group(Word.Document document, string[] names) 
{
    // namesはグループ化対象のShapeたちのNameが入っている
    object[] args = names.OfType<object>().ToArray();
    var range = document.Shapes.Range(args);
    range.Select();
    var group = range.Group(); // <-- ここで落ちる
}

例外の内容

System.UnauthorizedAccessException: 選択した図形はグループ化できません。

原因

2つあった。

Wordが見えてなかった

高速化の観点からWordを非表示にしていて実行していたが、Group化する際にはVisibleがtrueじゃないといけない(Wordが見えてないといけない)ようだ。

Shapeがあるページに遷移していない

グループ化対象のShapeが見えない位置にあると、上記のUnauthorizedAccessException が出るようで、例えば1ページ目にShapeがあれば成功するが、2ページ目にあると失敗するという現象が発生した。

対処

今回の場合、以下のようなVisible操作とページ遷移コードをrange.Group() の前に実行しておく必要があった。

Application.Visible = true;
Application.Selection.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, {該当ページ});
range.Group();

これで安定してグループ化することができました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?