1
4

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 5 years have passed since last update.

【メモ】配列を一気に格納→一気に貼り付け

Last updated at Posted at 2018-12-07

<FunctionとSubの適当な違い>
Functionは返り値がある。
Subはない。Callで呼び出す。
Publicが付く・付かないの違いはよく調べてないので今度調べる。
シートを配列に格納する方法について参考にさせて頂いたサイト:https://howto-it.com/excelvbaarray.html
ありがとうございました。

'シート全体を配列に読み込む関数
Public Function Sheet2Array(BookName As String, SheetName As String) As Variant

    Dim RowNum As Double
    Dim ColNum As Double

    With Workbooks(BookName).Sheets(SheetName)
        RowNum = .Cells(Rows.Count, 1).End(xlUp).Row
        ColNum = .Cells(1, Columns.Count).End(xlToLeft).Column
        Sheet2Array = .Range(.Cells(1, 1), .Cells(RowNum, ColNum))
    End With

End Function

↓なぜかcells(column(6),column(18))だと機能しなかった。。。
※追記。Range(columns(6),columns(18))が正しいです。

'新規シートを作成→シート名変更→配列をそこに貼り付け→不要列削除。
Sub ArryPaste(ByRef BookName As String, ByRef SheetName As String, ByRef Arry As Variant)

Dim ws As Worksheet
Dim wb As Workbook

Set wb = Workbooks(BookName)
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = SheetName


'新シートに配列を貼り付け → 不要列(6~18)削除
ws.Cells(1, 1).Resize(UBound(Arry, 1), UBound(Arry, 2)).Value = Arry
ws.Range("F:R").Delete

End Sub

宣言した変数を↑のSubプロシージャの引数の型と明示的に統一させないと、次のエラーが出てうまく機能しない。
エラー:「コンパイルエラーbyref引数の型が一致しません」

Sub 配列転記()

Dim Arry() As Variant
'配列に格納
Arry = Sheet2Array(Workbooks("●●●.xlsm").Name, "2018(H30)")

'宣言と代入を同時にするやり方↓
Dim BookName1 As String: BookName1 = "▲▲▲.xlsx"
Dim SheetName As String: SheetName = "□□□"


Call ArryPaste(BookName1, SheetName, Arry)

End Sub

1
4
2

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?