Sửa code Gộp File

Liên hệ QC
Tôi tuân thủ nội quy khi đăng bài

thang_nguyen1

Thành viên hoạt động
Tham gia
6/10/16
Bài viết
136
Được thích
8
Mình có một đoạn code về gộp File. Giờ mình muốn sửa sao cho khi gộp file chỉ lấy tiêu đề ở file thứ nhất thôi, từ file thứ hai sẽ bỏ qua tiều đề. Mong mọi người giúp đỡ mình, xin cảm ơn mọi người.
Mã:
Sub MergeSheetInFolder()
   
    Dim objFs As Object
    Dim objFolder As Object
    Dim File As Object
    Dim Wb As Workbook
    Dim ws As Worksheet
    Dim OpenWb As Workbook
    Dim OpenWs As Worksheet
    Dim xDir As String
    Dim Folder As Object
    Dim xRows As Long
    Dim xColumns As Long
    Dim xColumnsFirst As Long
    Dim WorkRng As Range
    Dim xTitleId As String
    Dim LastRowWb As Long
    Dim LastRowOpenWb As Long
   
    On Error Resume Next
   
    Set Wb = ActiveWorkbook
    Set ws = Wb.ActiveSheet
   
    xTitleId = "Vung merge"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Xin chon vung (1 sheet trong file nay) de paste data", xTitleId, WorkRng.Address, Type:=8)
   
    LastRowWb = ws.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
   
    If LastRowWb = 0 Then
        LastRowWb = 1
    Else
        LastRowWb = LastRowWb + 1
    End If
   
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .DisplayStatusBar = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
   
    Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
   
    If Folder.Show <> -1 Then
        With Application
            .ScreenUpdating = True
            .Calculation = xlCalculationAutomatic
            .DisplayStatusBar = True
            .DisplayAlerts = True
            .EnableEvents = True
        End With
        Exit Sub
    End If
   
    xDir = Folder.SelectedItems(1)
   
    Set objFs = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFs.GetFolder(xDir)

    For Each File In objFolder.Files
       
        Set OpenWb = Workbooks.Open(File.path, True, True)
        Set OpenWs = OpenWb.ActiveSheet
       
        LastRowOpenWb = OpenWs.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
       
        OpenWs.Rows("1:" & LastRowOpenWb).Copy
        Wb.Activate
       
        With ActiveSheet.Range("a" & LastRowWb)
            .PasteSpecial xlPasteAll
            .PasteSpecial xlPasteFormats
        End With
       
        LastRowWb = LastRowWb + LastRowOpenWb
       
        OpenWb.Close False
        Set OpenWb = Nothing
    Next
       
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With

    MsgBox "Done!"
   
End Sub
 
Upvote 0
Upvote 0
Cũng nên tùy thời mà thay đổi. VBA với người mới thì học khó hơn, dễ lỗi hơn. Còn Power query mới học chỉ cần nhấn nút tác vụ.
Anh có thể quay video các bước thực hiện việc nối file này bằng Power Query được không?
Nghe anh nói em thấy mình lạc hậu quá.
 
Upvote 0
Đây bạn ơi, giúp mình với.
Bạn thử lại được chưa nhe.

Mã:
Sub MergeSheetInFolder()
 
    Dim objFs As Object
    Dim objFolder As Object
    Dim File As Object
    Dim Wb As Workbook
    Dim ws As Worksheet
    Dim OpenWb As Workbook
    Dim OpenWs As Worksheet
    Dim xDir As String
    Dim Folder As Object
    Dim xRows As Long
    Dim xColumns As Long
    Dim xColumnsFirst As Long
    Dim WorkRng As Range
    Dim xTitleId As String
    Dim LastRowWb As Long
    Dim LastRowOpenWb As Long
'------------------------------
    Dim i As Long
'------------------------------
    On Error Resume Next
 
    Set Wb = ActiveWorkbook
    Set ws = Wb.ActiveSheet
 
    xTitleId = "Vung merge"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Xin chon vung (1 sheet trong file nay) de paste data", xTitleId, WorkRng.Address, Type:=8)
 
    LastRowWb = ws.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

    On Error GoTo Errorhandler

    If LastRowWb = 0 Then
        LastRowWb = 1
    Else
        LastRowWb = LastRowWb + 1
    End If
 
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .DisplayStatusBar = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
 
    Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
 
    If Folder.Show <> -1 Then
        With Application
            .ScreenUpdating = True
            .Calculation = xlCalculationAutomatic
            .DisplayStatusBar = True
            .DisplayAlerts = True
            .EnableEvents = True
        End With
        Exit Sub
    End If
 
    xDir = Folder.SelectedItems(1)
'----------------------------------------
    i = 0
'----------------------------------------
    Set objFs = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFs.GetFolder(xDir)

    For Each File In objFolder.Files
        
        If InStr(1, objFs.GetExtensionName(File), "csv", vbTextCompare) > 0 Then
            
'            Set OpenWb = Workbooks.Open(Filename:= _
'            File.Path, _
'            UpdateLinks:=0, IgnoreReadOnlyRecommended:=True, _
'            CorruptLoad:=XlCorruptLoad.xlExtractData)
    
            Set OpenWb = Workbooks.Open(Filename:=File.Path)
    
            Set OpenWs = OpenWb.ActiveSheet
            
            On Error Resume Next
    
            LastRowOpenWb = OpenWs.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
    
            If Err <> 0 Then
    
                LastRowOpenWb = 0
                OpenWb.Close False
                Set OpenWb = Nothing
    
            Else
                
                i = i + 1
                
                If i = 1 Then
                    OpenWs.Rows("1:" & LastRowOpenWb).Copy
                Else
                    OpenWs.Rows("2:" & LastRowOpenWb).Copy
                End If
    
                Wb.Activate
    
                With ActiveSheet.Range("A" & LastRowWb)
                    .PasteSpecial xlPasteAll
                    .PasteSpecial xlPasteFormats
                End With
    
                If i > 1 Then
                    LastRowWb = LastRowWb + LastRowOpenWb - 1
                Else
                    LastRowWb = LastRowWb + LastRowOpenWb
                End If
    
                OpenWb.Close False
                Set OpenWb = Nothing
    
            End If

            On Error GoTo 0
            
        End If
    Next
      
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With

    MsgBox "Done!"
 
    Exit Sub
    
Errorhandler:
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With
    
    MsgBox "Co loi xay ra, vui long kiem tra lai!"
    
    Exit Sub
 
End Sub
 
Upvote 0
Sửa code, giữ nguyên thuật toán và tên biến:
- Dẹp hết resume next
- Xóa bớt lệnh, khai báo không cần thiết
- Xóa bớt khối lệnh thừa
- Sửa 1 số câu lệnh
- Chặn trước 1 số lỗi
Gọn gàng hơn rất nhiều, mặc dù không tối ưu.
PHP:
Sub MergeSheetInFolder()
 
    Dim objFs As Object, objFolder As Object, File As Object, Folder As Object
    Dim Wb As Workbook, ws As Worksheet, OpenWb As Workbook, OpenWs As Worksheet
    Dim xDir As String, WorkRng As Range
    Dim LastRowWb As Long, LastRowOpenWb As Long, i As Long
'------------------------------'
    Set Wb = ActiveWorkbook
    Set ws = Wb.ActiveSheet
 
    Set WorkRng = Application.InputBox("Xin chon vung de paste data", "Data", "A1", Type:=8)
 
    On Error GoTo Errorhandler
    Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
 
    If Folder.Show <> -1 Then
        Exit Sub
    End If
     With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .DisplayStatusBar = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With

    xDir = Folder.SelectedItems(1)
    i = 0
'----------------------------------------'
    Set objFs = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFs.GetFolder(xDir)

    For Each File In objFolder.Files
       
        If objFs.GetExtensionName(File) = "csv" Then
           
            Set OpenWb = Workbooks.Open(Filename:=File.Path)
            Set OpenWs = OpenWb.ActiveSheet
            LastRowOpenWb = OpenWs.Cells(10000, 1).End(xlUp).Row
   
            If LastRowOpenWb = 1 Then
                OpenWb.Close False
                Set OpenWb = Nothing
            Else
                i = i + 1
                If i = 1 Then
                    LastRowWb = WorkRng.Row
                    OpenWs.Rows("1:" & LastRowOpenWb).Copy ws.Cells(LastRowWb, 1)
                Else
                    LastRowWb = ws.Cells(10000, 1).End(xlUp).Row + 1
                    OpenWs.Rows("2:" & LastRowOpenWb).Copy ws.Cells(LastRowWb, 1)
                End If
   
                OpenWb.Close False
                Set OpenWb = Nothing
            End If
        End If
    Next
    MsgBox "Done!"
Errorhandler:
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With
End Sub
 
Lần chỉnh sửa cuối:
Upvote 0
Sửa code, giữ nguyên thuật toán và tên biến:
- Dẹp hết resume next
- Xóa bớt lệnh, khai báo không cần thiết
- Xóa bớt khối lệnh thừa
- Sửa 1 số câu lệnh
- Chặn trước 1 số lỗi
Gọn gàng hơn rất nhiều, mặc dù không tối ưu.
PHP:
Sub MergeSheetInFolder()
 
    Dim objFs As Object, objFolder As Object, File As Object, Folder As Object
    Dim Wb As Workbook, ws As Worksheet, OpenWb As Workbook, OpenWs As Worksheet
    Dim xDir As String, WorkRng As Range
    Dim LastRowWb As Long, LastRowOpenWb As Long, i As Long
'------------------------------'
    Set Wb = ActiveWorkbook
    Set ws = Wb.ActiveSheet
 
    Set WorkRng = Application.InputBox("Xin chon vung de paste data", "Data", "A1", Type:=8)
 
    On Error GoTo Errorhandler
    Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
 
    If Folder.Show <> -1 Then
        Exit Sub
    End If
     With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .DisplayStatusBar = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With

    xDir = Folder.SelectedItems(1)
    i = 0
'----------------------------------------'
    Set objFs = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFs.GetFolder(xDir)

    For Each File In objFolder.Files
      
        If objFs.GetExtensionName(File) = "csv" Then
          
            Set OpenWb = Workbooks.Open(Filename:=File.Path)
            Set OpenWs = OpenWb.ActiveSheet
            LastRowOpenWb = OpenWs.Cells(10000, 1).End(xlUp).Row
  
            If LastRowOpenWb = 1 Then
                OpenWb.Close False
                Set OpenWb = Nothing
            Else
                i = i + 1
                If i = 1 Then
                    LastRowWb = WorkRng.Row
                    OpenWs.Rows("1:" & LastRowOpenWb).Copy ws.Cells(LastRowWb, 1)
                Else
                    LastRowWb = ws.Cells(10000, 1).End(xlUp).Row + 1
                    OpenWs.Rows("2:" & LastRowOpenWb).Copy ws.Cells(LastRowWb, 1)
                End If
  
                OpenWb.Close False
                Set OpenWb = Nothing
            End If
        End If
    Next
    MsgBox "Done!"
Errorhandler:
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With
End Sub
Dữ liệu cột 1 full thì được nhưng nếu bị thiếu từ dòng cuối trở lên là thua luôn.
 
Upvote 0
Ok để mai mình kiểm tra nhe.
OK cảm ơn bạn.

Bạn thử lại được chưa nhe.

Mã:
Sub MergeSheetInFolder()
 
    Dim objFs As Object
    Dim objFolder As Object
    Dim File As Object
    Dim Wb As Workbook
    Dim ws As Worksheet
    Dim OpenWb As Workbook
    Dim OpenWs As Worksheet
    Dim xDir As String
    Dim Folder As Object
    Dim xRows As Long
    Dim xColumns As Long
    Dim xColumnsFirst As Long
    Dim WorkRng As Range
    Dim xTitleId As String
    Dim LastRowWb As Long
    Dim LastRowOpenWb As Long
'------------------------------
    Dim i As Long
'------------------------------
    On Error Resume Next
 
    Set Wb = ActiveWorkbook
    Set ws = Wb.ActiveSheet
 
    xTitleId = "Vung merge"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Xin chon vung (1 sheet trong file nay) de paste data", xTitleId, WorkRng.Address, Type:=8)
 
    LastRowWb = ws.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

    On Error GoTo Errorhandler

    If LastRowWb = 0 Then
        LastRowWb = 1
    Else
        LastRowWb = LastRowWb + 1
    End If
 
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .DisplayStatusBar = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
 
    Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
 
    If Folder.Show <> -1 Then
        With Application
            .ScreenUpdating = True
            .Calculation = xlCalculationAutomatic
            .DisplayStatusBar = True
            .DisplayAlerts = True
            .EnableEvents = True
        End With
        Exit Sub
    End If
 
    xDir = Folder.SelectedItems(1)
'----------------------------------------
    i = 0
'----------------------------------------
    Set objFs = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFs.GetFolder(xDir)

    For Each File In objFolder.Files
       
        If InStr(1, objFs.GetExtensionName(File), "csv", vbTextCompare) > 0 Then
           
'            Set OpenWb = Workbooks.Open(Filename:= _
'            File.Path, _
'            UpdateLinks:=0, IgnoreReadOnlyRecommended:=True, _
'            CorruptLoad:=XlCorruptLoad.xlExtractData)
   
            Set OpenWb = Workbooks.Open(Filename:=File.Path)
   
            Set OpenWs = OpenWb.ActiveSheet
           
            On Error Resume Next
   
            LastRowOpenWb = OpenWs.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
   
            If Err <> 0 Then
   
                LastRowOpenWb = 0
                OpenWb.Close False
                Set OpenWb = Nothing
   
            Else
               
                i = i + 1
               
                If i = 1 Then
                    OpenWs.Rows("1:" & LastRowOpenWb).Copy
                Else
                    OpenWs.Rows("2:" & LastRowOpenWb).Copy
                End If
   
                Wb.Activate
   
                With ActiveSheet.Range("A" & LastRowWb)
                    .PasteSpecial xlPasteAll
                    .PasteSpecial xlPasteFormats
                End With
   
                If i > 1 Then
                    LastRowWb = LastRowWb + LastRowOpenWb - 1
                Else
                    LastRowWb = LastRowWb + LastRowOpenWb
                End If
   
                OpenWb.Close False
                Set OpenWb = Nothing
   
            End If

            On Error GoTo 0
           
        End If
    Next
     
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With

    MsgBox "Done!"
 
    Exit Sub
   
Errorhandler:
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With
   
    MsgBox "Co loi xay ra, vui long kiem tra lai!"
   
    Exit Sub
 
End Sub
Code chuẩn rồi bạn. Cảm ơn bạn nhiều
 
Upvote 0
Sửa code, giữ nguyên thuật toán và tên biến:
- Dẹp hết resume next
- Xóa bớt lệnh, khai báo không cần thiết
- Xóa bớt khối lệnh thừa
- Sửa 1 số câu lệnh
- Chặn trước 1 số lỗi
Gọn gàng hơn rất nhiều, mặc dù không tối ưu.
PHP:
Sub MergeSheetInFolder()
 
    Dim objFs As Object, objFolder As Object, File As Object, Folder As Object
    Dim Wb As Workbook, ws As Worksheet, OpenWb As Workbook, OpenWs As Worksheet
    Dim xDir As String, WorkRng As Range
    Dim LastRowWb As Long, LastRowOpenWb As Long, i As Long
'------------------------------'
    Set Wb = ActiveWorkbook
    Set ws = Wb.ActiveSheet
 
    Set WorkRng = Application.InputBox("Xin chon vung de paste data", "Data", "A1", Type:=8)
 
    On Error GoTo Errorhandler
    Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
 
    If Folder.Show <> -1 Then
        Exit Sub
    End If
     With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .DisplayStatusBar = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With

    xDir = Folder.SelectedItems(1)
    i = 0
'----------------------------------------'
    Set objFs = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFs.GetFolder(xDir)

    For Each File In objFolder.Files
     
        If objFs.GetExtensionName(File) = "csv" Then
         
            Set OpenWb = Workbooks.Open(Filename:=File.Path)
            Set OpenWs = OpenWb.ActiveSheet
            LastRowOpenWb = OpenWs.Cells(10000, 1).End(xlUp).Row
 
            If LastRowOpenWb = 1 Then
                OpenWb.Close False
                Set OpenWb = Nothing
            Else
                i = i + 1
                If i = 1 Then
                    LastRowWb = WorkRng.Row
                    OpenWs.Rows("1:" & LastRowOpenWb).Copy ws.Cells(LastRowWb, 1)
                Else
                    LastRowWb = ws.Cells(10000, 1).End(xlUp).Row + 1
                    OpenWs.Rows("2:" & LastRowOpenWb).Copy ws.Cells(LastRowWb, 1)
                End If
 
                OpenWb.Close False
                Set OpenWb = Nothing
            End If
        End If
    Next
    MsgBox "Done!"
Errorhandler:
    With Application
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
        .DisplayStatusBar = True
        .DisplayAlerts = True
        .EnableEvents = True
        .CutCopyMode = False
    End With
End Sub
Cho em hỏi thêm khi em không chạy gộp file em bấm cancel thì nó ra lỗi này. Thầy sửa giúp em chút cho em được không ạcancel2.PNG
 
Lần chỉnh sửa cuối:
Upvote 0
Web KT

Bài viết mới nhất

Back
Top Bottom