Excel文件合併(基於宏)

Private Function SelectDir() As String
Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    With fd    '用戶按下的是操作按鈕 (-1) 還是取消按鈕 (0)
        If .Show = -1 Then
            SelectDir = .SelectedItems(1) & "\"
        End If
    End With
    Set fd = Nothing
End Function

Sub SearchFile()

Dim MyFolder, MyFile As String
Dim i As Integer

    MyFolder = SelectDir()
    Sheets("文件列表").Cells(1, 2) = MyFolder

    i = 1
    MyFile = Dir(MyFolder)
    Do While MyFile <> ""
        Sheets("文件列表").Cells(i, 1) = MyFile
        MyFile = Dir
        i = i + 1
    Loop

End Sub

Sub CombineSheets()

Dim MyFolder, MyFile, CurBook As String
Dim RowCount, FileCount, i As Integer

    With Sheets("文件列表")
         MyFolder = .Range("B1").Value
        FileCount = .[A65535].End(xlUp).Row
       .Range("B:B").ClearContents
        .Range("B1").Value = "合併出錯"
    End With

    CurBook = ActiveWorkbook.Name

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
    End With
   
    On Error GoTo ErrOpen
    For i = 1 To FileCount
        With Workbooks(CurBook)
            'RowCount = .Sheets("合併內容").[A65535].End(xlUp).Row
            'MyFile = .Sheets("文件列表").Cells(i, 1)
            'Application.Workbooks.Open (MyFolder & MyFile)
            'Workbooks(MyFile).Sheets(1).UsedRange.Copy
            '.Sheets("合併內容").Cells(RowCount + 1, 1).PasteSpecial
            '.Sheets("合併內容").Rows(RowCount + 1).EntireRow.Delete
            'Application.Workbooks(MyFile).Close savechanges:=False
            '.Sheets("文件列表").Cells(i, 2) = "合併完成"
         
           
            MyFile = .Sheets("文件列表").Cells(i, 1)
              'MsgBox i, vbInformation, "hcccc"
            Application.Workbooks.Open (MyFolder & MyFile)
              'MsgBox i, vbInformation, "haaaa"
            Workbooks(MyFile).Sheets(1).Columns("B:B").Copy
             ' MsgBox i, vbInformation, "hbbbb"
            .Sheets("合併內容").Columns(i).PasteSpecial              '黏貼
            Application.Workbooks(MyFile).Close savechanges:=False
            .Sheets("文件列表").Cells(i, 2) = "合併完成"
           
        End With
    Next i

ErrOpen:
    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
    End With

End Sub

Sub ClearFileList()
    With Sheets("文件列表")
        .Range("A:A").ClearContents
        .Range("B:B").ClearContents
    End With
End Sub

Sub ClearDetail()
    Sheets("合併內容").Cells.ClearContents
End Sub

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章