|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
- Sub CopyData()
- Dim fd As FileDialog
- Dim folderPath As String
- Set fd = Application.FileDialog(msoFileDialogFolderPicker)
-
- fd.Title = "请选择数据文件夹"
- fd.InitialFileName = ThisWorkbook.Path
-
- '显示选择文件夹对话框
- If fd.Show = -1 Then
- folderPath = fd.SelectedItems(1)
- Else
- MsgBox "未选择数据文件夹,程序退出"
- Set fd = Nothing
- Exit Sub
- End If
-
- '获取数据文件
- Dim fileName As String
- fileName = Dir(folderPath & "\*.xls*")
-
- Dim wsList As Worksheet, wsTest As Worksheet
- Dim targetWorkbook As Workbook
- Dim targetSheet As Worksheet
- Dim lastRow As Long
- Dim lastCol As Long
- Dim i As Long, j As Long
- Dim matchFound As Boolean
- Set wsList = ThisWorkbook.Worksheets("清单")
- Dim targetValue As Variant
- targetValue = ThisWorkbook.Sheets("数据录入").Range("C3").Value
- ScreenUpdating = False
- Dim myArr(), myCopyArr(), myCopyArrTrns()
- ReDim myCopyArr(1 To 1000, 1 To 100) '根据数据量大小预设一下数组的大小
- Dim n As Long '匹配目标计数器
- n = 0
-
- Do While fileName <> ""
- Set targetWorkbook = Workbooks.Open(folderPath & "" & fileName)
- Set targetSheet = targetWorkbook.Worksheets("测试")
- myArr = targetSheet.UsedRange
- lastRow = UBound(myArr, 1)
- lastCol = UBound(myArr, 2)
-
- For i = 2 To lastRow
- If myArr(i, 6) = targetValue Then
- n = n + 1 '找到一条匹配的记录,计数器加1
- If n > UBound(myCopyArr, 1) Then '如果记录数组容量不够用就扩容
- myCopyArrTrns = Application.Transpose(myCopyArr) '由于扩容只能扩展数组最后一维,无法直接扩展第一维,所以进入数组转置
- ReDim Preserve myCopyArrTrns(LBound(myCopyArr, 1) To UBound(myCopyArr, 2), LBound(myCopyArr, 1) To UBound(myCopyArr, 1) * 2) '现有容量翻倍
- myCopyArr = Application.Transpose(myCopyArrTrns)
- End If
-
- For j = 1 To lastCol
- myCopyArr(n, j) = myArr(i, j) '复制匹配的数据
- Next
- End If
- Next i
-
- targetWorkbook.Close SaveChanges:=False
- Set targetSheet = Nothing
- Set targetWorkbook = Nothing
- MsgBox "扫描完一个文件,开始扫描下一个文件" & "目前已有" & n & "条记录"
- fileName = Dir()
- Loop
- MsgBox "扫描完毕,共找到" & n & "条匹配的数据"
- wsList.Range("a4").Resize(n, lastCol).Value = myCopyArr
- ScreenUpdating = True
- End Sub
复制代码 |
|