Nhờ sửa code VBA lấy dữ liệu từ file excel khác

Chia sẻ bởi:hands
★★★★★
Quảng cáo

Mình muốn lấy dữ liệu vùng B19:I785 vào file MAIN.xlsm

Trong file MAIN.xlsm, tại sheet "Main" nhấn nút "Get DATA" sẽ brown file tới Foder đích để chọn tầm 22 file có cấu trúc giống hệt nhau. Sau đó copy dữ liệu từ 22 file này tới sheet DATA trong file MAIN.xlsm (sheet DATA chưa có sẽ tạo hoặc có rồi sẽ delete tạo lại)

Đây là code mình sưu tầm được:

Private Declare Function SetCurrentDirectoryA Lib _
    "kernel32" (ByVal lpPathName As String) As Long

Sub ChDirNet(szPath As String)
    SetCurrentDirectoryA szPath
End Sub

Sub MergeSpecificWorkbooks()
    Dim MyPath As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long
    Dim SaveDriveDir As String
    Dim FName As Variant

' Set application properties.
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

SaveDriveDir = CurDir
    ' Change this to the pathfolder location of the files.
    ChDirNet "C:Usersalone"

FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                                        MultiSelect:=True)
    If IsArray(FName) Then

' Delete the summary sheet if it exists.
    Application.DisplayAlerts = False
    On Error Resume Next
    ActiveWorkbook.Worksheets("DATA").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

' Add a new summary worksheet.
    Set DestSh = ActiveWorkbook.Worksheets.Add
    DestSh.Name = "DATA"

' Loop through all files in the myFiles array.
        For FNum = LBound(FName) To UBound(FName)
            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(FName(FNum))
            On Error GoTo 0

If Not mybook Is Nothing Then

On Error Resume Next
                With mybook.Worksheets(1)
                    Set sourceRange = .Range("B19:I785")
                End With

If Err.Number > 0 Then
                    Err.Clear
                    Set sourceRange = Nothing
                Else
                    ' If the source range uses all columns then
                    ' skip this file.
                    If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                        Set sourceRange = Nothing
                    End If
                End If
                On Error GoTo 0

If Not sourceRange Is Nothing Then

SourceRcount = sourceRange.Rows.Count

If rnum + SourceRcount >= BaseWks.Rows.Count Then
                        MsgBox "There are not enough rows in the target worksheet."
                        BaseWks.Columns.AutoFit
                        mybook.Close savechanges:=False
                        GoTo ExitTheSub
                    Else

' Copy the file name in column A.
                        With sourceRange
                            BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = FName(FNum)
                        End With

' Set the destination range.
                        Set destrange = BaseWks.Range("B" & rnum)

' Copy the values from the source range
                        ' to the destination range.
                        With sourceRange
                            Set destrange = destrange. _
                                            Resize(.Rows.Count, .Columns.Count)
                        End With
                        destrange.Value = sourceRange.Value
                        rnum = rnum + SourceRcount
                    End If
                End If
                mybook.Close savechanges:=False
            End If

Next FNum
        BaseWks.Columns.AutoFit
    End If

ExitTheSub:
    ' Restore the application properties.
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
    ChDirNet SaveDriveDir
End Sub

Code này nó báo lỗi tại dòng BaseWks.Columns.AutoFit => mình đã bôi đỏ

Nhờ các bạn giúp sửa code với ạ, đính kèm file để các bạn dễ hình dung.

Cảm ơn nhiều ạ./.

Không thấy chỗ nào màu đỏ cả. 😀
Trên diễn đàn có rất rất nhiều bài tổng hợp dữ liệu từ nhiều file rồi. Bạn chịu khó tìm xem… copy về là xài được luôn. Mới đây nhất có bạn cần tổng hợp từ 600 "anh em" files ấy.
Chờ người sửa code chắc chờ tới 2 mùa quýt.

cảm ơn bạn replay nhé, 4rum mình cũng kiếm rồi mà chưa ưng ý lắm kiếm code này về xem sao ấy mà.

Nếu bạn có thời gian thì giúp với nhé, mình có đính kèm file đó chạy bị lỗi. À nãy lúc post threat có bôi đỏ đoạn code báo lỗi mà post lên đen thui hết. sorry

Lỗi ở chỗ này nè
Set sourceRange = .Range("B19:I785") (bạn lấy rang thì đoạn code dưới Columns.count sao được nữa nếu biết 8 cột thì dùng luon

If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If

Cảm ơn bạn nhiều, vì file cần lấy có số liệu tới row 785 thôi bạn, từ row 786 là các dòng text chú thích với comment mà mình chỉ muốn lấy data thôi.
À có xíu lỗi "oánh mái" dư chữ "a" hi hi

Mình đính kèm 3 file cân đối lên bạn xem thử với ạ.
Bạn có cách gì sửa nguyên code chạy không ạ

Public Sub GPE()
Dim cn As Object, rs As Object, I As Byte, lR As Long
Set cn = CreateObject("adodb.connection")
    With Application.FileDialog(msoFileDialogOpen)
        .InitialFileName = ThisWorkbook.Path
        .Filters.Clear
        .Filters.Add "GPE", "*.xls*"
        .AllowMultiSelect = True
        .Show
        For I = 1 To .SelectedItems.Count
            cn.Open ("provider=Microsoft.ACE.OLEDB.12.0;data source=" & .SelectedItems(I) & ";mode=Read;extended properties=""Excel 12.0;hdr=no"";")

Set rs = cn.Execute("select * from [G000141$A19:I785] ")

lR = Range("A" & Rows.Count).End(3).Row
            If Not rs.EOF Then Range("A" & lR + 1).CopyFromRecordset rs
            rs.Close
            cn.Close
        Next
    End With
End Sub

www.giaiphapexcel.com/diendan/threads/nh%E1%BB%9D-s%E1%BB%ADa-code-vba-l%E1%BA%A5y-d%E1%BB%AF-li%E1%BB%87u-t%E1%BB%AB-file-excel-kh%C3%A1c.130631/

Ứng dụng AI và Chat GPT trong Quản trị nhân sự
Khóa học SprinGO phù hợp

Ứng dụng AI và Chat GPT trong Quản trị nhân sự

Học xong khóa này, học viên có thể: Hiểu đúng bản chất AI, các nhóm AI phổ biến và cách AI “hoạt động” ở...

Xem khóa học
★★★★★ 5 ★ 1 👤 3 ▥ 0
Quảng cáo

Bạn nên đọc

Bình luận

Quảng cáo

Cũ vẫn chất

Xem thêm