|
- Option Explicit
- Sub Test()
- Dim SH As Worksheet, strShName As String
- Dim lngRows As Long, lngRow As Long, strTemp As String
- Dim arrResult As Variant, strCondition As String, intCount As Integer
- Dim Conn As Object, Rst As Object, strPath As String
- Dim strConn As String, strSQL As String, strBasicSql As String
- Dim rgResult As Range
-
- strShName = "老师小类表"
- Set SH = Sheets(strShName)
-
- ''''''''''''''''''''''''''''''''''''''''''''''''''''
- lngRows = SH.Range("I" & Rows.Count).End(xlUp).Row
- If lngRows < 2 Then Exit Sub '条件区域无值
- arrResult = SH.Range("I2:K" & lngRows)
- Set rgResult = SH.Range("I2")
-
- lngRows = SH.Range("C" & Rows.Count).End(xlUp).Row
- If lngRows < 2 Then Exit Sub '数据区域无值
- strShName = strShName & "$A1:C" & lngRows
-
- ''''''''''''''''''''''''''''''''''''''''''''''''''''
- 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
- ''''''''''''''''''''''''''''''''''''''''''''''''''''
- strBasicSql = "SELECT 老师姓名 " & _
- "FROM [@strShName@] " & _
- "WHERE 小类 In (@strCondition@) " & _
- "GROUP BY 老师姓名 " & _
- "HAVING Count(小类) >= @intCount@ " & _
- "ORDER BY 老师姓名;"
-
- ''''''''''''''''''''''''''''''''''''''''''''''''''''
- Application.ScreenUpdating = False
- Application.Cursor = xlWait
-
- For lngRow = LBound(arrResult) To UBound(arrResult)
- strTemp = arrResult(lngRow, 1)
- strTemp = Trim(strTemp)
- strTemp = Replace(strTemp, ";", ";") '将全角分号改为半角
- intCount = UBound(Split(strTemp, ";")) + 1 '计算条件数
- strTemp = Replace(strTemp, ";", Chr(34) & "," & Chr(34))
- strCondition = Chr(34) & strTemp & Chr(34)
-
- strSQL = Replace(strBasicSql, "@strShName@", strShName)
- strSQL = Replace(strSQL, "@strCondition@", strCondition)
- strSQL = Replace(strSQL, "@intCount@", intCount)
-
- Rst.Open strSQL, Conn, 3, 1 '执行查询,并将结果输出到记录集对象
- strTemp = ""
- If Rst.RecordCount > 0 Then
- Rst.movefirst
- Do Until Rst.EOF
- strTemp = strTemp & ";" & Rst.Fields("老师姓名").Value
- Rst.movenext
- Loop
- End If
- Rst.Close
- arrResult(lngRow, 3) = Mid(strTemp, 2)
- Next
- Set Rst = Nothing
- Set Conn = Nothing
-
- ''''''''''''''''''''''''''''''''''''''''''''''''''''''
- rgResult.Resize(UBound(arrResult), UBound(arrResult)) = arrResult
- MsgBox "OK"
-
- Application.ScreenUpdating = True
- Application.Cursor = xlDefault
-
- End Sub
复制代码 |
|