计算来自多个csv文件的数据

时间:2012-10-12 21:46:30

标签: excel vba excel-vba

我在共享文件夹中有数百个链接到它们的文件夹 例如:

a:\Images\abc\year\month\date\names1
a:\Images\abc\year\month\date\names2
a:\Images\abc\year\month\date\names3 etc,.

每个文件夹中都有一个csv(每个文件夹中的 abc.csv 常量名称),其中包含的信息很少。

例如:

1 Orange USA
2 Apple England
3 Orange Australia
4 Orange Austria
5 Apple India

在这里,我想以CSV为单位计算橘子,苹果,葡萄和甜瓜的数量 不同的文件夹。

我期待输出如:

Link    Oranges Apples  Grapes  Melon

\names1 5846    2000    85215   586

\Names2 4521    1542    45852   125

\Names3 365     4856    25415   548

请帮助......

1 个答案:

答案 0 :(得分:2)

试试这段代码。它将打开列(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