1. 程式人生 > >vba-多個工作簿合併方法1(用到了陣列)

vba-多個工作簿合併方法1(用到了陣列)

來自《別怕excel vba其實很簡單》

Sub 多個工作簿合併()
'
  '多個工作簿合併 巨集
  Dim bt As Range, r As Long, c As Long
  r = 1
  c = 7
  Dim wt As Worksheet
  Set wt = ThisWorkbook.Worksheets(1)
  wt.Rows(r + 1 & ":1048576").ClearContents
  Application.ScreenUpdating = False
  Dim filename As String, sht As Worksheet, wb As Workbook


  Dim erow As Long, fn As String, arr As Variant
  filename = Dir(ThisWorkbook.Path & "\*.xlsx")   'dir-獲取檔名
    'MsgBox ("這個是:" & ThisWorkbook.Path)-->"這個是C;\...desktop\新建資料夾"
  Do While filename <> ""
    If filename <> ThisWorkbook.Name Then
    erow = wt.Range("a1").CurrentRegion.Rows.Count + 1   '當前區域的行數+1-->獲得彙總表第一行的行號?

    fn = ThisWorkbook.Path & "\" & filename   '將第1個要彙總的工作簿名稱賦給變數fn
    Set wb = GetObject(fn)   '將變數fn代表的工作簿物件賦給wb
    Set sht = wb.Worksheets(1)   '將要彙總工作表賦給sht
    arr = sht.Range(sht.Cells(1, "A"), sht.Cells(1048576, "b").End(xlUp).Offset(0, 5))
     '將工作表中要彙總的記錄儲存在陣列arr中
    wt.Cells(erow, 1).Resize(UBound(arr, 1), UBound(arr, 2)) = arr '?

    wb.Close False
    End If
    filename = Dir '用dir函式取得其他檔名,並賦給變數??
  Loop
  Application.ScreenUpdating = True

End Sub