|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
- Sub 多行_多列_多条件_查询_ADO法_同夹_多薄_指定表_参考()
- 时间 = Timer
- Range("A9:I65536").Clear
- Application.ScreenUpdating = False
- Dim objWMI As Object
- Const HKEY_LOCAL_MACHINE = &H80000002
- Set objWMI = GetObject("winmgmts:\\.\root\default:StdRegProv")
- 条件数组 = Range("A1:E7")
- For 行 = 1 To UBound(条件数组)
- If 条件数组(行, 2) <> "" Then 条件1 = 条件1 & " and " & 条件数组(行, 1) & "='" & 条件数组(行, 2) & "'"
- If 条件数组(行, 3) <> "" Then 条件2 = 条件2 & " and " & 条件数组(行, 1) & "='" & 条件数组(行, 3) & "'"
- If 条件数组(行, 4) <> "" Then 条件3 = 条件3 & " and " & 条件数组(行, 1) & "='" & 条件数组(行, 4) & "'"
- If 条件数组(行, 5) <> "" Then 条件4 = 条件4 & " and " & 条件数组(行, 1) & "='" & 条件数组(行, 5) & "'"
- Next 行
- If 条件1 & 条件2 & 条件3 & 条件4 = "" Then Exit Sub
- 条件1 = Mid(条件1, 5): 条件2 = Mid(条件2, 5): 条件3 = Mid(条件3, 5): 条件4 = Mid(条件4, 5)
- If 条件4 = "" And 条件3 <> "" And 条件2 <> "" And 条件1 <> "" Then
- 条件组合 = 条件1 & "Or" & (条件2) & "Or" & (条件3)
- ElseIf 条件4 = "" And 条件3 = "" And 条件2 <> "" And 条件1 <> "" Then
- 条件组合 = 条件1 & "Or" & (条件2)
- ElseIf 条件4 = "" And 条件3 = "" And 条件2 = "" And 条件1 <> "" Then
- 条件组合 = 条件1
- ElseIf 条件4 <> "" And 条件3 <> "" And 条件2 <> "" And 条件1 <> "" Then
- 条件组合 = 条件1 & "Or" & (条件2) & "Or" & (条件3) & "Or" & (条件4)
- End If
- If Application.Version < 12 Then
- 连接方式 = "Provider=Microsoft.jet.OLEDB.4.0;Extended Properties='excel 8.0;imex=1';Data Source="
- objWMI.SetDWORDValue HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Jet\4.0\Engines\Excel", "TypeGuessRows", 0
- Else
- 连接方式 = "Provider=Microsoft.ace.OLEDB.12.0;Extended Properties='excel 12.0;imex=1';Data Source="
- objWMI.SetDWORDValue HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Office" & Application.Version & "\Access Connectivity Engine\Engines\Excel", "TypeGuessRows", 0
- End If
- 路径 = ThisWorkbook.Path & ""
- 外薄 = Dir(路径 & "*.xls*")
- Do While 外薄 <> ""
- If InStr(外薄, ThisWorkbook.Name) = 0 Then
- Set 连接 = CreateObject("adodb.connection")
- 连接.Open 连接方式 & 路径 & 外薄
- Set 记录 = 连接.OpenSchema(20)
- Do Until 记录.EOF
- If 记录.Fields("TABLE_TYPE") = "TABLE" Then
- 外表 = Replace(记录("TABLE_NAME").Value, "'", "")
- If Right(外表, 1) = "$" Then
- Set rst = 连接.Execute("[" & 外表 & "a1:a]")
- If Err.Number = 0 Then
- If rst.Fields(0).Name = "字段1" Then
- SQL = "select 字段3,字段5,'" & Replace(外薄, ".xls", "") & "','" & Replace(外表, "$", "") & "' from [" & 外表 & "] where" & 条件组合
- Set rst = 连接.Execute(SQL)
- If Not rst.EOF Then Range("a65536").End(3).Offset(1).CopyFromRecordset rst
- End If
- Else
- Err.Clear
- End If
- End If
- End If
- 记录.MoveNext
- Loop
- End If
- 外薄 = Dir()
- Loop
- 记录.Close: Set 记录 = Nothing
- rst.Close: Set rst = Nothing
- 连接.Close: Set 连接 = Nothing
- Application.ScreenUpdating = True
- MsgBox Timer - 时间
- End Sub
复制代码 |
|