Excel宏可对一个文件夹中多个Excel文件中特定列的列值进行计数

时间:2018-08-21 13:52:33

标签: excel vba excel-vba

enter image description here

Public Sub Sum_Demo()
    Dim myRange
    Dim Results
    Dim Run As Long

    For Run = 1 To 3
        Select Case Run
        Case 1
            myRange = Worksheets("Sheet1").Range("A1", "A100")
        Case 2
            myRange = Worksheets("Sheet1").Range("A1", "A300")
        Case 3
            myRange = Worksheets("Sheet1").Range("A1", "A25")
        End Select
        Results = WorksheetFunction.Sum(myRange)
        Range("B" & Run) = Results
    Next Run
End Sub

请建议使用一个Excel宏来从一个文件夹中的不同Excel文件中查找PID列值的计数。每个文件中的列名都相同。 PID列中的值数会有所不同。我需要输出(单独的excel文件)作为 例如:

Customer count
ABC       30
PBC       50       

1 个答案:

答案 0 :(得分:0)

由于缺乏信息,很难提出解决方案。但是这里的概念应该可以帮助您到达那里。我有三个excel工作簿,每个工作簿只有一个名为sheet1的工作表。两个没有数据。一个表没有标题,如下所示:

ABC | 1

ABC | 2

ABC | 3

ABC | 12

PBC | 4

PBC | 5

如果有标题,请用标题名称替换[F1],[F2]等。也要仔细调试第二个功能。

Sub main()
    Dim cn                                  As ADODB.connection
    Dim abcCount                            As Long
    Dim pbcCount                            As Long
    Dim strFile                             As String
    Dim filePath                            As String
    Dim inputDirectoryToScanForFile         As String

    inputDirectoryToScanForFile = "Z:\Test\"

    strFile = Dir(inputDirectoryToScanForFile & "*.xlsx")

    Do While strFile <> ""
        filePath = inputDirectoryToScanForFile & strFile

        Set cn = New ADODB.connection

        cn.Open _
                "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source='" & filePath & "';" & _
                "Extended Properties=""Excel 12.0 Macro;HDR=No;IMEX=1;"";"

        abcCount = abcCount + findCount(cn, "ABC")
        pbcCount = pbcCount + findCount(cn, "PBC")

        cn.Close
        strFile = Dir
    Loop

    Debug.Print "ABC COUNT " & abcCount
    Debug.Print "PBC COUNT " & pbcCount
End Sub

Function findCount(ByRef cn As ADODB.connection, ByVal searchKey As String) As Long
    On Error GoTo CleanFail:
    Dim strSql As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset
    strSql = "SELECT COUNT([F2]) FROM [Sheet1$] WHERE [F1] = '" & searchKey & "';"
    rs.Open strSql, cn
    findCount = CInt(rs.GetString)
    rs.Close
    Exit Function
CleanFail:
End Function