【VBA】二次元配列をシートに貼り付け【範囲をリサイズする】
作成日:2022-12-04
更新日:2025-10-03

1つのセルを配列の大きさにリサイズする
' Write a 2D Variant array to a worksheet range safely (auto-sizes via bounds)
' 2次元Variant配列を安全にシートへ書き込む(下限・上限からサイズ算出)
Public Sub Paste2DArray( _
ByVal ws As Worksheet, _
ByVal topRow As Long, _
ByVal leftCol As Long, _
ByRef ary As Variant)
' Guard clauses|ガード節
If ws Is Nothing Then Exit Sub
If Not IsArray(ary) Then Exit Sub
On Error GoTo CleanExit
Dim l1 As Long, u1 As Long ' row bounds|行方向の下限・上限
Dim l2 As Long, u2 As Long ' col bounds|列方向の下限・上限
l1 = LBound(ary, 1): u1 = UBound(ary, 1)
l2 = LBound(ary, 2): u2 = UBound(ary, 2)
Dim rowCount As Long, colCount As Long
rowCount = u1 - l1 + 1
colCount = u2 - l2 + 1
If rowCount <= 0 Or colCount <= 0 Then Exit Sub
' Performance toggles|パフォーマンス切替
Dim prevCalc As XlCalculation
Dim prevUpdating As Boolean
prevCalc = Application.Calculation
prevUpdating = Application.ScreenUpdating
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' Write in one shot|一括書き込み
With ws
.Cells(topRow, leftCol).Resize(rowCount, colCount).Value = ary
End With
CleanExit:
' Restore app state|アプリ状態復元
On Error Resume Next
Application.Calculation = prevCalc
Application.ScreenUpdating = prevUpdating
On Error GoTo 0
End Sub
安全な計算式|Safe sizing
- 行数(RowSize)=
UBound(ary,1) - LBound(ary,1) + 1
- 列数(ColumnSize)=
UBound(ary,2) - LBound(ary,2) + 1
- 0始まり/1始まり、いずれも正しく
Resize
できる。(Microsoft Learn)
| Lower Bound|下限 |
| Upper Bound|上限 |
| RowSize|行数 |
| ColumnSize|列数 |
| Rectangular Array|矩形配列 |
| ScreenUpdating|画面更新 |
| Calculation Mode|計算モード |
| Guard Clause|ガード節 |
| Intent-Revealing Names|意図の見える命名 |
| One-shot Write|一括書き込み |
resize once
and blast the array in one go
and blast the array in one go

一次元配列の場合

同じ処理をPythonでも書いてみよう
2022-12-04
編集後記:
この記事の内容がベストではないかもしれません。