需要帮助优化vba显示功能

时间:2016-06-08 21:11:02

标签: excel vba performance function

我一直在做excel的数据库工作,作为数据库和数据库驱动程序通过宏与vba。我构建了一个函数,它应该解析带有testID字段的数据库记录列表。我想根据它的testID只显示每个测试一次,但数据库的设置方式意味着我必须消除重复的testID。我这样做是通过迭代记录集并在列表中显示之前检查当前测试与前一个测试。我遇到的问题是功能极其缓慢。对于数据库中的仅12个测试,在视图电子表格中显示它们大约需要3秒钟。我很想听听如何优化运行时的一些想法。这是功能:

Public Function showAllTests()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cstring, sql As String
Dim r, c As Integer
Dim testsAr As Variant
Dim inAr As Boolean

cstring = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source=I:\DBtrials.xlsx; Extended Properties=""Excel 12.0 Xml; HDR=YES;ReadOnly=False"";"

sql = "SELECT [TestID], [Status], [PFIBox], [WireType], [StartingDia], [Customer], [numSamples], [Assigned] FROM [Tests$]"

Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset

Call conn.Open(cstring)
Set rs = conn.Execute(sql)

If rs.EOF Then
    Range("C6:J1000").ClearContents
End If

r = 6
count = 0
'Iterates through the recordset, eliminating duplicates and populating cells in the tests sheet
While Not rs.BOF And Not rs.EOF
        Dim prevID, currID As String
        Dim currCell As Range

        inAr = False

        If Not count = 0 Then
            prevID = ActiveWorkbook.Sheets("Tests").Cells(r - 1, 3).Value
            currID = CStr(rs(0))
            If prevID = currID Then
                inAr = True
            End If
        End If

        For c = 3 To (rs.Fields.count + 2)

            Set currCell = ActiveWorkbook.Sheets("Tests").Cells(r, c)

            If Not IsNull(rs(c - 3).Value) And inAr = False Then
                currCell.Value = CStr(rs(c - 3))
                ElseIf IsNull(rs(c - 3).Value) Then currCell.Value = ""
                    Else:
                        Exit For
            End If
        Next c

        If inAr = False Then
            r = r + 1
        End If
        rs.MoveNext

        count = count + 1
Wend



conn.Close
Set conn = Nothing

结束功能

1 个答案:

答案 0 :(得分:1)

使用GROUP BY

sql =" SELECT [TestID],[Status],[PFIBox],[WireType],[StartingDia],[Customer],[numSamples],[Assigned] FROM [Tests $] GROUP BY [TestID] ]"

其中一些驱动程序--Microsoft.ACE.OLEDB.12.0等在VBA中也有可怕的性能。有时我从OBDC 6.2获得比ADO更好的性能