|
- Sub test2() 'ADO + SQL
- Dim Conn As Object, rs As Object, SQL As String, sStr As String
- Dim wks As Worksheet, ar, titleRow As Long, splitCol As Long
- titleRow = 1 '标题所在 行
- splitCol = 5 '拆分依据 E列
- DoApp False
- Worksheets("Sheet1").Activate
- For Each wks In Worksheets
- If wks.Name <> ActiveSheet.Name Then wks.Delete
- Next
- Set Conn = CreateObject("ADODB.Connection")
- Set rs = CreateObject("ADODB.Recordset")
- If Application.Version < 12 Then
- Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & ThisWorkbook.FullName
- Else
- Conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & ThisWorkbook.FullName
- End If
- ar = Range("A1").CurrentRegion.Resize(titleRow)
- sStr = ActiveSheet.Name & "$" & Range("A1").CurrentRegion.Offset(titleRow - 1).Address(0, 0)
- SQL = "SELECT DISTINCT [" & ar(titleRow, splitCol) & "] FROM [" & sStr & "] WHERE LEN([" & ar(titleRow, splitCol) & "])"
- rs.Open SQL, Conn, 1, 3
- SQL = "SELECT 序号,名称,规格,数量 FROM [" & sStr & "] WHERE [" & ar(titleRow, splitCol) & "]='[sStr]'"
- While Not rs.EOF
- sStr = rs.Fields(0).Value
- Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = sStr
- With ActiveSheet
- .Range("A1").Resize(, 4) = Split("序号 名称 规格 数量")
- .Range("A" & titleRow + 1).CopyFromRecordset Conn.Execute(Replace(SQL, "[sStr]", sStr))
- '.Columns.AutoFit
- End With
- rs.MoveNext
- Wend
- rs.Close
- Set rs = Nothing
- Conn.Close
- Set Conn = Nothing
- Worksheets(1).Activate
- DoApp
- Beep
- End Sub
- Function DoApp(Optional b As Boolean = True)
- With Application
- .ScreenUpdating = b
- .DisplayAlerts = b
- .Calculation = -b * 30 - 4135
- End With
- End Function
复制代码 |
评分
-
1
查看全部评分
-
|