2011年12月29日 星期四

如何合併同一個資料夾下的所有excel檔案內的工作表

於工作需要, 所以又硬著頭皮寫出以下的EXCEL VBA , 發現不錯用, 分享出來:
Private Sub Workbook_Open()

Call ClearWorkSheet
Call CopyWorkSheet


End Sub


Sub ClearWorkSheet()
Application.DisplayAlerts = False
For Each Ws In ThisWorkbook.Worksheets
If Ws.Name <> "首 頁" Then
  Ws.Delete
End If
Next
Application.DisplayAlerts = True
       
End Sub

Sub CopyWorkSheet()

Dim SRC  As Workbook
Dim DES  As Workbook
Dim WKS  As Worksheet
'Set SRC = Workbooks.Open(ActiveWorkbook.Path & "\HKG.xls")
Set DES = ThisWorkbook
Set WKS = ThisWorkbook.Worksheets(1)
'SRC.Activate
'SRC.Worksheets.Copy BEFORE:=DES.Worksheets(1)
'SRC.Worksheets(1).Copy BEFORE:=DES.Worksheets(1)

'SRC.Close

Set fso = CreateObject("Scripting.FileSystemObject")
    Dim strText As String
    Dim i As Integer
   
    Set flds = fso.GetFolder(ActiveWorkbook.Path).Files
    i = 1
   
    For Each f In flds
        If f.Name <> "TARGET.xls" Then
            Set SRC = Workbooks.Open(f.Path)
            SRC.Worksheets.Copy BEFORE:=DES.Worksheets(1)
            SRC.Close
    '            strText = strText & i & "." & f.Name & vbCrLf
        End If
           i = i + 1
    Next
       
End Sub

沒有留言: