|
- Option Explicit
- Sub Test()
- Dim sh As Worksheet, strShName As String, strAddress As String
- Dim Conn As Object, Rst As Object, strPath As String
- Dim strConn As String, strSQL As String
- Dim lngRows As Long, lngCols As Long
- Dim arrTitle As Variant '标题区域
- Dim arrType As Variant '类型,用于命名工作表
- Dim lngID As Long, strFind As String
-
- strShName = "数据源"
- Set sh = Sheets(strShName)
- lngRows = sh.Range("A1").CurrentRegion.Rows.Count - 1 '采用无标题行的方式,所以总行数要减1
- lngCols = sh.Range("A1").CurrentRegion.Columns.Count
-
- arrTitle = sh.Range("A1").Resize(1, lngCols) '读取标题行
- strAddress = sh.Range("A2").Resize(lngRows, lngCols).Address(0, 0) '获取数据区域地址
-
- 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=NO"";"""
- End Select
- Conn.Open strConn
- '获取代号
- strSQL = "SELECT [F1] FROM [" & strShName & "$" & strAddress & "] GROUP BY [F1];"
- If Rst.State = 1 Then Rst.Close
- Rst.Open strSQL, Conn, 3, 1 '执行查询,并将结果输出到记录集对象
-
- If Rst.RecordCount = 0 Then
- Set Rst = Nothing
- Set Conn = Nothing
- MsgBox "无数据!", vbInformation + vbOKOnly, "提示"
- Exit Sub
- End If
-
- arrType = Rst.GetRows
-
- For lngID = LBound(arrType, 2) To UBound(arrType, 2)
- strFind = arrType(0, lngID)
- '逐个类型读取数据,并写入不同的表
- strSQL = "SELECT * FROM [" & strShName & "$" & strAddress & "] WHERE [F1] Like '" & strFind & "';"
- If Rst.State = 1 Then Rst.Close
- Rst.Open strSQL, Conn, 3, 1 '执行查询,并将结果输出到记录集对象
- FullDataToSheet strFind, arrTitle, Rst
- Next
-
- Set Rst = Nothing
- Set Conn = Nothing
-
- MsgBox "OK"
- End Sub
- Function FullDataToSheet(strShName As String, arrTitle As Variant, arrData As Object)
- Dim sh As Worksheet
-
- On Error Resume Next
-
- If Not Sheets(strShName) Is Nothing Then
- If Err.Number <> 9 Then
- Set sh = Sheets(strShName)
- Else
- Set sh = Sheets.Add(After:=Sheets(Sheets.Count))
- sh.Name = strShName
- End If
- Err.Clear
- End If
-
- sh.UsedRange.Clear
- sh.Range("A1").Resize(UBound(arrTitle), UBound(arrTitle, 2)) = arrTitle '标题
- sh.Range("A2").CopyFromRecordset arrData '数据
-
- Set sh = Nothing
- End Function
复制代码 |
|