|
在二楼基础上,SQL语句优化
- Private Sub CommandButton1_Click()
- Dim Conn As Object, Rst As Object, strPath As String
- Dim strConn As String, strSQL As String, strSQL_E As String
- Dim lngRow As Long
-
- Set Conn = CreateObject("ADODB.Connection")
- Set Rst = CreateObject("ADODB.Recordset")
- strPath = ThisWorkbook.FullName '设置工作簿的完整路径和名称
- Select Case Application.Version * 1 '设置连接字符串,根据版本创建连接
- Case Is <= 11
- strConn = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties=excel 8.0;Data source=" & strPath
- Case Is >= 12
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
- End Select
- Conn.Open strConn '打开数据库链接
- Sheet7.Range("A3:N51").ClearContents '清空区域的数据
- For i = 1 To Sheets.Count
- If Sheets(i).Name <> "全校榜" Then strSQL = strSQL & "SELECT [学号],[班 次],[姓 名],[语 文],[英 语],[数 学],[总 分] FROM [" & Sheets(i).Name & "$A4:G41] " & " UNION ALL "
- Next i
- strSQL = Left(strSQL, Len(strSQL) - 11) '因为循环倒数第二个工作表时,sq语句最后还是链接到 union all ,一共有11个字符,这时要提取sq字符串中不包含最后11个字符的字符串
- strSQL = strSQL & " ORDER BY [总 分] DESC,[学号] ASC"
-
- strSQL_E = "Select Top 50 [班 次],[姓 名],[语 文],[英 语],[数 学],[总 分] From (" & strSQL & ") "
- Rst.Open strSQL_E, strConn, adOpenStatic, adLockReadOnly
- Sheet7.Range("A3").CopyFromRecordset Rst
- Rst.Close
-
- strSQL_E = "Select Top 50 [班 次],[姓 名],[语 文],[英 语],[数 学],[总 分] From (" & strSQL & ") Where [学号] NOT In (Select Top 50 [学号] From (" & strSQL & "))"
- Rst.Open strSQL_E, strConn, adOpenStatic, adLockReadOnly
- Sheet7.Range("H3").CopyFromRecordset Rst
-
- Conn.Close
- Set Conn = Nothing
-
- For lngRow = 1 To 50
- Sheet7.Range("G" & lngRow + 2) = lngRow
- Sheet7.Range("N" & lngRow + 2) = lngRow + 50
- Next
- End Sub
复制代码 |
|