|
本帖最后由 zhaogang1960 于 2013-1-17 16:56 编辑
假设都有“公司名称”字段,查找该字段是否存在指定公司名称,如果有则列出文件名、工作表名(xls文件):- Sub Macro1()
- Dim cnn As Object, cnncsv As Object, cat As Object, rs As Object, SQL$, MyFile, arr$(), i&, m&, n&
- ChDrive Split(ThisWorkbook.Path, ":")(0)
- ChDir ThisWorkbook.Path
- MyFile = Application.GetOpenFilename(fileFilter:="xls、csv文件(*.xls;*.csv),*.xls;*.csv", Title:="选择xls、csv文件", MultiSelect:=True) 'MultiSelect:=True——多选
- If TypeName(MyFile) = "Boolean" Then Exit Sub
- ReDim arr(1 To UBound(MyFile), 1 To 2)
- temp = [b2]
- Application.ScreenUpdating = False
- myPath = ThisWorkbook.Path & ""
- Set cnn = CreateObject("adodb.connection")
- Set cat = CreateObject("ADOX.Catalog")
- Set cnncsv = CreateObject("adodb.connection")
- cnncsv.Open ConnectionString:="Provider=MSDASQL;Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & myPath
- For i = 1 To UBound(MyFile)
- If MyFile(i) <> ThisWorkbook.FullName Then
- If LCase(MyFile(i)) Like "*.xls" Then
- n = n + 1
- If n = 1 Then cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & MyFile(i)
- cat.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=No';Data Source=" & MyFile(i)
- For Each tb1 In cat.Tables
- If tb1.Type = "TABLE" Then
- s = Replace(tb1.Name, "'", "")
- If Right(s, 1) = "[ DISCUZ_CODE_0 ]quot; Then
- SQL = "select * from [Excel 8.0;Database=" & MyFile(i) & "].[" & s & "] where 公司名称='" & temp & "'"
- Set rs = CreateObject("adodb.recordset")
- rs.Open SQL, cnn, 1, 3
- If rs.RecordCount Then
- m = m + 1
- a = Split(MyFile(i), "")
- arr(m, 1) = a(UBound(a))
- arr(m, 2) = s
- Exit For
- End If
- End If
- End If
- Next
- ElseIf LCase(MyFile(i)) Like "*.csv" Then
- SQL = "select * from " & MyFile(i) & " where 公司名称='" & temp & "'"
- Set rs = CreateObject("adodb.recordset")
- rs.Open SQL, cnncsv, 1, 3
- If rs.RecordCount Then
- m = m + 1
- a = Split(MyFile(i), "")
- arr(m, 1) = a(UBound(a))
- End If
- End If
- End If
- Next
- Range("A4:B65536").ClearContents
- Range("A4").Resize(m, 2) = arr
- Set cat = Nothing
- Set tb1 = Nothing
- rs.Close
- Set rs = Nothing
- cnn.Close
- Set cnn = Nothing
- cnncsv.Close
- Set cnncsv = Nothing
- Application.ScreenUpdating = True
- End Sub
复制代码 |
|