TOP ▲
itcore TOP
> TIPS
> excel_vba_join.php
タグ:excel vba join EXCEL VBA 複数のシートをjoinで連結する。(ファイル出力) | itcore 2019年
参考
EXCEL VBA スクリプトの実行
データシート

実行結果

ファイルにも出力します。
ファイル
Excelファイル
ソースコード
Option Explicit
Sub main()
  Dim i, sheet, cell, row, col, max_row, max_col, item, s1, key, data
  Dim items: items = Array("ID", "名前", "OS")
  Dim cols_os: Set cols_os = CreateObject("Scripting.Dictionary")
  
  ' ファイル出力
  Dim file: file = ThisWorkbook.Path & "\join.txt"
  Open file For Output As #1
  ' ヘッダ出力
  s1 = items(0)
  For i = 1 To UBound(items)
    s1 = s1 & vbTab & items(i)
  Next
  Debug.Print s1
  Print #1, s1
  ' マスタデータの読み込み
  Set sheet = Sheets("OS")
  max_row = Rows.Count
  For row = 2 To max_row
    key = sheet.Cells(row, 1)
    If "" = key Then Exit For
    data = sheet.Cells(row, 2)
    cols_os(key) = data
  Next
  ' データシートのループ
  Set sheet = Sheets("サーバ")
  max_row = Rows.Count
  For row = 2 To max_row
    item = items(0)
    col = 1
    cell = sheet.Cells(row, col)
    If "" = cell Then Exit For ' 最初の項目のデータがなくなったところで終了
    s1 = cell
    For i = 1 To UBound(items)
      item = items(i)
      col = i + 1
      cell = sheet.Cells(row, col)
      If ("OS" = item) Then
        cell = cell & ":" & cols_os(cell)
      End If
      s1 = s1 & vbTab & cell
    Next
    Debug.Print s1
    Print #1, s1
  Next
  
  Close
  Debug.Print file & "を作成しました。"
End Sub
~