|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
- Sub SQL法()
- Dim Fso As Object, File As Object, cnn As Object, rs As Object, rst As Object, SQL$, arr, a, b, s$, m&, n&, i&, j&, r, tb$
- Application.ScreenUpdating = False
- arr = Sheets("Rule").[a7].CurrentRegion
- a = Array("", "", "'", "'", "#", "'", "'", "")
- b = Array("SEGMENT1", "VENDOR_NAME", "INVOICE_DATE", "INVOICE_NUM", "INVOICE_CURRENCY_CODE", "INVOICE_AMOUNT")
- For i = 2 To UBound(arr)
- s = s & " or "
- m = 0
- For j = 2 To 7
- If Len(arr(i, j)) Then
- m = m + 1
- If m = 1 Then
- s = s & b(j - 2) & "=" & a(j) & arr(i, j) & a(j)
- Else
- s = s & " and " & b(j - 2) & "=" & a(j) & arr(i, j) & a(j)
- End If
- End If
- Next
- Next
- If s = "" Then Exit Sub
- r = 2
- Set Fso = CreateObject("Scripting.FileSystemObject")
- With Sheets("Result")
- .UsedRange.Offset(1).ClearContents
- For Each File In Fso.GetFolder(ThisWorkbook.Path).Files
- If File.Name Like "*.xlsx" Then
- Set cnn = CreateObject("adodb.connection")
- cnn.Open "provider=microsoft.ace.oledb.12.0;extended properties=excel 12.0;data source=" & File
- Set rst = cnn.OpenSchema(20)
- Do Until rst.EOF
- If rst.Fields("TABLE_TYPE") = "TABLE" Then
- tb = rst("TABLE_NAME").Value
- If Right(tb, 1) = "$" Then
- SQL = "select " & Join(b, ",") & " from [" & tb & "] where " & Mid(s, 4)
- Set rs = CreateObject("adodb.recordset")
- rs.Open SQL, cnn, 1, 3
- If rs.RecordCount Then
- .Range("A" & r).CopyFromRecordset rs
- r = r + rs.RecordCount
- End If
- End If
- End If
- rst.MoveNext
- Loop
- End If
- Next
- End With
- rs.Close
- rst.Close
- cnn.Close
- Set rs = Nothing
- Set rst = Nothing
- Set cnn = Nothing
- Set File = Nothing
- Set Fso = Nothing
- Application.ScreenUpdating = True
- End Sub
复制代码 |
|