|
- Sub test1() 'SQL写法练习,仅供参考,通用Excel和WPS……
- Dim Files_(), Path_ As String
- Path_ = ThisWorkbook.Path & "\测试\"
- If Not GetFileName(Files_, Path_, ".xls") Then MsgBox "!": Exit Sub
-
- Dim results(), ar, br(1), cel As Range
- Dim i As Long, j As Long, cnt As Long, vrt, Item_
- Dim Conn As Object, re As Object, dict As Object
- Dim strConn As String, SQL As String, s As String
-
- Set Conn = CreateObject("ADODB.Connection")
- Set dict = CreateObject("Scripting.Dictionary")
- Set re = CreateObject("VBScript.RegExp")
- re.Global = True
- re.Pattern = "(\D+)(\d+)(\D+)(\d+)"
-
- ar = Split("I3:I4 C3 C5 I5:I6 A9 E9 C9 I9 C16:C17 E16:E17 C18:C19 E18:E19 C20:C21 E20:E21 C22:C23 E22:E23 C27:M27 C28:M28 C30:M30 C33:M33")
- For Each Item_ In ar
- For Each cel In Range(Item_)
- s = cel.Address(, , xlR1C1)
- For j = 4 To 2 Step -2
- br(-CInt(j = 2)) = re.Replace(s, "$" & j) - 1
- Next
- dict.Add Join(br, "|"), dict.Count + 2
- Next
- Next
- ReDim results(1 To 2345, 1 To dict.Count + 1)
- Set re = Nothing
-
- ActiveSheet.UsedRange.Offset(3).Clear 'Contents
- Application.ScreenUpdating = False
-
- s = "Excel 12.0;HDR=NO;IMEX=1;Database="
- If Application.Version < 12 Or InStr(Application.Path, "WPS") > 0 Then
- s = Replace(s, "12.0", "8.0")
- strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=NO';Data Source="
- Else
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=NO';Data Source="
- End If
- Conn.Open strConn & Files_(LBound(Files_))
-
- SQL = "SELECT * FROM [" & s & "[.File]].[$A1:M40]"
- For j = LBound(Files_) To UBound(Files_)
- If Files_(j) <> ThisWorkbook.FullName Then
- cnt = cnt + 1
- results(cnt, 1) = cnt
- ar = Conn.Execute(Replace(SQL, "[.File]", Files_(j))).GetRows
- For Each Item_ In dict.Keys
- vrt = Split(Item_, "|")
- results(cnt, dict(Item_)) = ar(vrt(0), vrt(1))
- Next
- End If
- Next
-
- Range("A4").Resize(cnt, UBound(results, 2)) = results
- With Range("A1").CurrentRegion
- With Intersect(.Offset(0), .Offset(3))
- .Borders.LineStyle = xlContinuous
- .HorizontalAlignment = xlCenter
- .Font.Size = 9
- End With
- End With
-
- Conn.Close
- Set Conn = Nothing
- Set dict = Nothing
- Application.ScreenUpdating = True
- Beep
- End Sub
- Function GetFileName(Files_, Path_ As String, ext As String) As Boolean
- Dim File_ As String, j As Long, k As Long, ar(9999) As String
- If Right(Path_, 1) <> "\" Then Path_ = Path_ & "\"
- Do
- File_ = Dir(Path_, vbDirectory)
- Do
- If File_ <> "." And File_ <> ".." Then
- If (GetAttr(Path_ & File_) And vbDirectory) = vbDirectory Then
- k = k + 1
- ar(k) = Path_ & File_ & "\"
- Else
- If LCase(Right(File_, Len(ext))) = LCase(ext) Then '限于目前的.xls格式 可改灵活
- j = j + 1
- ReDim Preserve Files_(1 To j)
- Files_(j) = Path_ & File_
- End If
- End If
- End If
- File_ = Dir
- Loop While Len(File_)
- If k = 0 Then Exit Do
- Path_ = ar(k)
- k = k - 1
- Loop
- GetFileName = CBool(j)
- End Function
复制代码 |
|