从txt文件计算出现次数

时间:2013-11-04 03:48:09

标签: vba ms-access access-vba

我正在制作一个带按钮的简单表格。当单击comCount(按钮)时,我希望我的程序打开一个txt文件并返回表格中的文本(tblResults)并显示.txt中的每个值的计数..(animals.txt)

.txt文件中的输入如下所示

Cat
Cat
Dog
Bird
Fish
Cat
Dog

等等。每行只有一只动物

我不知道该怎么做,所以如果有人能帮助我的话,我将不胜感激。 然后tblResult应该返回

Cat 3
Dog 2
Bird 1
Fish 1

谢谢!

1 个答案:

答案 0 :(得分:0)

Private Sub comCount_Click()
    Dim sFileName As String
    Dim sAnimal As String
    Dim sQuery As String
    Dim dbs As DAO.Database
    Dim rsSQL As DAO.Recordset
    Dim iCount As Integer

    Set dbs = CurrentDb

    sFileName = "C:\Animals.txt" 'Enter your full path here
    Open sFileName For Input As #1

    While Not EOF(1)
        Line Input #1, sAnimal
        sQuery = "Select * from tblResults where AnimalName = """ & sAnimal & """"
        Set rsSQL = dbs.OpenRecordset(sQuery)
        If rsSQL.RecordCount = 0 Then
            rsSQL.AddNew
                rsSQL.Fields("AnimalName") = sAnimal
                rsSQL.Fields("AnimalCount") = 1
            rsSQL.Update
        Else
            rsSQL.Edit
                Count = rsSQL.Fields("AnimalCount") + 1
                rsSQL.Fields("AnimalCount") = iCount
            rsSQL.Update
        End If
        rsSQL.Close
    Wend

    Close #1

End Sub

还假设您的表中有两个字段,AnimalName和AnimalCount