【问题标题】:Need help optimizing vba display function需要帮助优化vba显示功能
【发布时间】:2016-06-08 21:11:01
【问题描述】:

我一直在使用 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

结束函数

【问题讨论】:

    标签: excel vba performance function


    【解决方案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 更好的性能

    【讨论】:

      猜你喜欢
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多