|
Sub SearchFiles()
'查询条件
Dim keyword1 As String
Dim keyword2 As String
keyword1 = "条件1"
keyword2 = "条件2"
'文件夹路径
Dim folderPath As String
folderPath = "文件夹路径"
'新建工作表
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "汇总表"
'遍历文件夹内的文件
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim folder As Object
Set folder = fs.GetFolder(folderPath)
Dim file As Object
For Each file In folder.files
'判断文件类型
If InStr(1, file.Name, ".csv", vbTextCompare) > 0 Or InStr(1, file.Name, ".xls", vbTextCompare) > 0 Or InStr(1, file.Name, ".xlsx", vbTextCompare) > 0 Then
'打开文件
Dim wb As Workbook
Set wb = Workbooks.Open(file.Path)
Dim wsData As Worksheet
Set wsData = wb.Sheets(1)
'查找关键字
Dim rngSearch As Range
Set rngSearch = wsData.Rows(1).Find(keyword1, LookIn:=xlValues, LookAt:=xlWhole)
If Not rngSearch Is Nothing Then
Dim colNum As Integer
colNum = rngSearch.Column
'复制数据到汇总表
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("A" & lastRow + 1 & ":Z" & lastRow + 1).Value = wsData.Range(wsData.Cells(2, 1), wsData.Cells(wsData.Rows.Count, colNum)).Value
End If
'查找关键字
Set rngSearch = wsData.Rows(1).Find(keyword2, LookIn:=xlValues, LookAt:=xlWhole)
If Not rngSearch Is Nothing Then
Dim colNum As Integer
colNum = rngSearch.Column
'复制数据到汇总表
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("A" & lastRow + 1 & ":Z" & lastRow + 1).Value = wsData.Range(wsData.Cells(2, 1), wsData.Cells(wsData.Rows.Count, colNum)).Value
End If
'关闭文件
wb.Close False
End If
Next file
End Sub
以上是ChatGPT回答 |
|