试试这个代码。它将打开列 (1) 中列出的每个文件夹中包含的文件 abc.csv,计算项目数,然后关闭文件并继续。
Option Explicit
Sub CountApples()
Dim wbk As Workbook, sht As Worksheet, wbkTemp As Workbook, lLoop As Long, lLastRow As Long
'turn off updates to speed up code execution
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
Set sht = ActiveSheet
lLastRow = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row
For lLoop = 2 To lLastRow
Set wbkTemp = Workbooks.Open(sht.Cells(lLoop, 1) & "\abc.csv")
sht.Cells(lLoop, 2).Value = Application.WorksheetFunction.CountIf(wbkTemp.Sheets(1).Columns(1), "Oranges")
sht.Cells(lLoop, 3).Value = Application.WorksheetFunction.CountIf(wbkTemp.Sheets(1).Columns(1), "Apples")
sht.Cells(lLoop, 4).Value = Application.WorksheetFunction.CountIf(wbkTemp.Sheets(1).Columns(1), "Grapes")
sht.Cells(lLoop, 5).Value = Application.WorksheetFunction.CountIf(wbkTemp.Sheets(1).Columns(1), "Melon")
wbkTemp.Close (False)
Next lLoop
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
End Sub