Chào các bác.
Em muốn sử dụng VBA để tự động tổng hợp số liệu từ các file được chọn vào một file.
Đây là file mẫu và đoạn code của em. Trong folder này có 3 file, em muốn lần lượt copy data ở các ô E33, J33, O33 trong file kqdq_alt.csv và kqdq_bcb.csv vào dòng cuối cùng không chứa dữ liệu ở trong file master.xlsx
Đây là phần khai báo biến và truy cập vào đường link chứa file.
Option Explicit Sub import_data() Dim master As Worksheet, sh As Worksheet Dim wk As Workbook Dim strFolderPath As String Dim selectedFiles As Variant Dim iFileNum As Integer, iLastRowReport As Integer, iNumberOfRowsToPaste As Integer Dim strFileName As String Dim rCopiedRange As range Dim iCurrentLastRow As Integer, iRowStartToPaste As Integer Dim startTime As Double Dim i As Integer Set master = ActiveWorkbook.ActiveSheet strFolderPath = ActiveWorkbook.Path ChDrive strFolderPath ChDir strFolderPathỞ đây em lưu các file được chọn vào một biến có tên là "selectedFiles. Đồng thời "On Error GoTo NoFileSelected" để thông báo lỗi
On Error GoTo NoFileSelected selectedFiles = Application.GetOpenFilename( _ filefilter:="All Files (*.csv*),*.csv*", MultiSelect:=True)Đoạn dưới là để truy cập vào từng file và lấy số liệu
For iFileNum = LBound(selectedFiles) To UBound(selectedFiles) strFileName = selectedFiles(iFileNum) Set wk = Workbooks.Open(strFileName) For Each sh In wk.Sheets If sh.Name Like "kqdq_*" Then With sh For i = 1 To 3 Cells(60, i) = 2014 - i Cells(61, i) = Cells(33, 5 * i).Value Next i Set rCopiedRange = .range(Cells(61, 1), Cells(61, 3)) End With [COLOR=#ff0000] With master iCurrentLastRow = .range("A100").End(xlUp).Row iRowStartToPaste = (iCurrentLastRow + 2) .range("A" & iRowStartToPaste).Resize(1, 3) = rCopiedRange.Value2 End With[/COLOR][B] End If Next sh wk.Close Next iFileNum NoFileSelected: MsgBox "No file selected"[/B] End SubCác cao thủ giúp em với ạ. Em nghĩ suốt 2 ngày rồi mà không hiểu sai ở đâu.+-+-+-+ phần tô đỏ có gì sai ko ạ?
Mình thấy mọi người viết thế này
For iFileNum = LBound(selectedFiles) To UBound(selectedFiles)
Workbooks.Open selectedFiles(yiFileNum)
With ActiveWorkbook
For Each sh In .Worksheets
'Code here
Next
.Close False
End With
Next
Thử thêm dấu chấm trước các cụm Cells() thế này
.Cells(60, i) = 2014 – i
selectedFiles = Application.GetOpenFilename( _
filefilter:="All Files (*.csv*),*.csv*", MultiSelect:=True)
Bạn kiểm tra lại đoạn này xem sao
www.giaiphapexcel.com/diendan/threads/nh%E1%BB%9D-c%C3%A1c-cao-th%E1%BB%A7-s%E1%BB%ADa-1-%C4%91o%E1%BA%A1n-code-ng%E1%BA%AFn.100403/
Khóa học Power PI – Ứng dung trong Nhân sự
TỔNG QUAN KHÓA HỌC: POWER BI CHO NGÀNH NHÂN SỰ Khóa học Power BI cho Nhân sự được thiết kế dành riêng cho các...
Xem khóa học