(Excel VBA)図形を画面中央に表示する方法 - tsukimisoba/Blog GitHub Wiki

前提条件

図形はすでに存在しており、名前は "gaaru" とします。

図形のサイズは高さ100px、幅100px。

ワークシートはセル A1 が表示されている状態からスタート。

Sub CenterShapeOnScreen()
    Dim ws As Worksheet
    Dim shp As Shape
    Dim targetRow As Long
    Dim centerCol As Long
    Dim screenRows As Long
    Dim screenCols As Long

    Set ws = ActiveSheet
    targetRow = 200

    ' 図形を取得
    Set shp = ws.Shapes("gaaru")

    ' 図形のサイズ設定(必要なら)
    shp.Height = 100
    shp.Width = 100

    ' 画面の中央列を計算(仮に画面に10列表示されていると仮定)
    screenCols = 10
    centerCol = screenCols \ 2

    ' 図形の位置を設定(セルの左上に合わせる)
    With ws.Cells(targetRow, centerCol)
        shp.Top = .Top + (.Height - shp.Height) / 2
        shp.Left = .Left + (.Width - shp.Width) / 2
    End With

    ' 図形が画面中央に来るようにスクロール
    ' 画面に表示される行数を仮に30行とし、図形が中央になるように調整
    screenRows = 30
    ws.Activate
    ws.Range("A" & targetRow - screenRows \ 2).Select
End Sub