|
楼主 |
发表于 2015-5-30 15:30
|
显示全部楼层
附上之前论坛老师提供的代码(修改红色部分后运行后数据消失):
Dim strSQL, s, Mypath$, OutputSheet$, OutputRange$, strCondition$
Sub 载入数据()
strSQL = "select * " & _
" from"
strCondition = "WHERE 车间 IS NOT NULL "
OutputSheet = "结果"
OutputRange = "A2"
Call subProgram(strSQL, OutputSheet, OutputRange, strCondition)
MsgBox "OK"
End Sub
Sub subProgram(ByVal strSQL$, ByVal OutputSheet$, ByVal OutputRange$, ByVal strCondition$)
Dim cnn As Object, rst As Object, rs As Object
Dim strConn As String, SQL$
Dim i As Integer, j%, Pathstr, s$, t$, sProvider$
Pathstr = Application.GetOpenFilename(fileFilter:="Excel文件(*.xls;*.xlsx;*.xlsm),*.xls;*.xlsx;*.xlsm", Title:="打开Excel文件", MultiSelect:=True) '选择多个EXCCEL 文件
If TypeName(Pathstr) = "Boolean" Then Exit Sub
Application.ScreenUpdating = False
Select Case Application.Version * 1
Case Is <= 11
sProvider = "Provider = Microsoft.Jet.Oledb.4.0;Extended Properties ='Excel 8.0';Data Source ="
Case Is >= 12
sProvider = "Provider = Microsoft.Ace.Oledb.12.0;Extended Properties ='Excel 12.0';Data Source ="
End Select
On Error Resume Next
With Sheets(OutputSheet)
.Cells.ClearContents
For i = 1 To UBound(Pathstr)
If Pathstr(i) <> ThisWorkbook.FullName Then
Set cnn = CreateObject("ADODB.Connection")
cnn.Open sProvider & Pathstr(i)
Set rs = cnn.OpenSchema(20)
Do Until rs.EOF
If rs.Fields("TABLE_TYPE") = "TABLE" Then
s = Replace(rs("TABLE_NAME").Value, "'", "")
If Right(s, 1) = "$" Then
SQL = strSQL & "[" & s & "] " & strCondition
Set rst = cnn.Execute(SQL)
If Err.Number = 0 Then
m = m + 1
If m = 1 Then
For j = 0 To rst.Fields.Count - 1
.Cells(1, j + 1) = rst.Fields(j).Name
Next
.Range("A2").CopyFromRecordset rst
Else
.Range("A1048576").End(xlUp).Offset(1).CopyFromRecordset rst
End If
' Exit Do'此句不能启用,记住了!否则有一个工作簿有二个表的,只能提取到一个。
Else
Err.Clear
End If
End If
End If
rs.MoveNext
Loop
End If
Next
Cells.EntireColumn.AutoFit
End With
rst.Close
rs.Close
cnn.Close
Set cnn = Nothing
Set rs = Nothing
Set rst = Nothing
Application.ScreenUpdating = True
End Sub
|
|