
【マクロ実践編2】連想配列とファイルの作成
A列内でデータは重複している。
A列の値が同じである行データごとに一つのファイルにして、ファイル名はA列の値にしたい件
A列を元に重複しないリストを作り、リストの数だけエクセルファイルを作る。
◆準備
参照設定:[Microsoft Scripting Runtime]
◆連想配列作成
Dim dic As Scripting.Dictionary
Set dic = CreateObject("Scripting.Dictionary")
Dim i As Long
Dim NameKey As String
For i = 0 To Range("A" & Rows.Count).End(xlUp).Row
NameKey = Range("A2").Offset(i).Value 'A1は項目名
If Not dic.Exists(NameKey) Then
dic.Add NameKey, NameKey '「値」は「キー」と同じ「名前」を登録
End If
Next
◆エクセルファイル作成
Dim newFile As String
Dim myPath As String
myPath = ThisWorkbook.Path
Dim cnt As Long
For cnt = 0 To dic.Count - 1
newFile = myPath & "\" & dic.Keys(cnt)
Workbooks.Add
ActiveWorkbook.SaveAs newFile, xlOpenXMLWorkbookMacroEnabled
( '拡張子は2番目のパラメータで指定します)
ActiveWorkbook.Close
Next
まとめ
重複しているデータを削除できないときに連想配列は使える。