我一直在尝试优化以下代码:
Public cn As New ADODB.Connection
Public rs As New ADODB.Recordset
Public rs2 As New ADODB.Recordset
Public strsQL$
...
For c = 9 To 50
strsQL = "some SQL query"
rs.Open strsQL, cn
For r = 2 To 1000
t = 0
If c <> 9 Then
For f = 9 To c - 1
t = t + Sheet9.Cells(8 + (r - 2) * 6, f)
Next f
End If
Set rs2 = rs.Clone
rs2.Find ("x='" & Sheet9.Cells(r, 2) & "'")
If rs2.EOF Then
Sheet9.Cells(r, c) = ""
Else
If rs2.Fields("Total").Value - t <> 0 Then
Sheet9.Cells(r, c) = rs2.Fields(1).Value - t
End If
End If
Next r
rs.Close
rs2.Close
Next c
cn.Close
Close Connection
Set rs = Nothing
Set cn = Nothing
Set rs2 = Nothing
这是我的想法(或者实际上是因为它比较慢):
...
For c = 9 To 50
strsQL = "some SQL query "
rs.Open strsQL, cn
Do While rs.EOF = False
t = 0
If Not ThisWorkbook.Sheet9.Range("B:B").Find(what:=rs.Fields(0).Value,
LookIn:=xlValues, lookat:=xlWhole) Is Nothing Then
P_row = ThisWorkbook.Sheet9.Range("B:B").Find(what:=rs.Fields(0).Value, LookIn:=xlValues, lookat:=xlWhole).Row
adr_1 = ThisWorkbook.Sheet9.Cells(P_row + 4, 9).Address
adr_2 = ThisWorkbook.Sheet9.Cells(P_row + 4, c - 1).Address
t = Application.WorksheetFunction.Sum(ThisWorkbook.Sheet9.Range(adr_1 & ":" & adr_2))
If rs.Fields(1).Value - t > 0 Then
Sheet9.Cells(P_row, c) = rs.Fields(1).Value - t
End If
End If
rs.MoveNext
Loop
rs.Close
Next c
cn.Close
Set rs = Nothing
Set cn = Nothing
我不明白为什么第二个代码的运行时间更糟。第一个代码遍历每一列,并为每一列打开记录集,并遍历工作表中B列的每一行,以查找记录集中是否包含行值。因此,即使记录集中未包含搜索的行,也可以通过rs.find命令对整个记录集进行搜索。 因为每个记录集的记录少于1000条,所以我可以肯定每个记录集的每一列都更好,并且只将找到的记录的值放进去,因为其余的记录可以留空。但这似乎是不正确的。
我还使用了application.worksheetfunction.sum而不是在循环中求和,但我不希望它有那么大的意义。
也许有人可以帮助我发现我的理解有什么问题?