|
用SQL语句-跨excel工作簿有条件地导取所需数据的问题求助(发在vba版块,没有人能回答我,所以只好拿到access sql这里来碰碰运气啦,烦请大师们出马指教,该问题烦了我两天了!
附档文件夹中有两个excel工作簿文件:not distribute 及10-05,我要通过not distribute 从10-05中有条件地导取数据,在执行以下代码时,必须将数据源10-05同时打开才可以,不打开,则不能导取到所要的数据。麻烦高手指教,多谢啦!
Sub GetData1()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim myWorkName As String, n As Integer, Sql As String
Dim wbName As String
Dim ws As Worksheet
Set ws = Worksheets("sheet1")
wbName = ThisWorkbook.Path & "\10-05.xls" '指定要查询的工作簿完整名称
ws.Cells.Clear
'建立与当前工作簿的连接
Set cnn = New ADODB.Connection
With cnn
.Provider = "microsoft.jet.oledb.4.0"
.ConnectionString = "Extended Properties=Excel 8.0;" _
& "Data Source=" & wbName
.Open
End With
myWorkName = "月度物料号明细" '指定要查询的工作表名称
'设置SQL语句
Sql = "select Material,[material desc],[Not distribute-all] from [" & myWorkName & "$] where [Not distribute-all]<> Null"
Set rs = New ADODB.Recordset
rs.Open Sql, cnn, adOpenKeyset, adLockOptimistic
n = rs.RecordCount
If n > 0 Then
MsgBox "查询到 " & n & " 条符合条件的记录。", vbInformation
Else
MsgBox "没有查询到符合条件的记录。", vbInformation
End If
'复制标题
For i = 1 To rs.Fields.Count
ws.Cells(1, i) = rs.Fields(i - 1).Name
Next i
'复制查询到的记录
ws.Range("A2").CopyFromRecordset rs
rs.Close
cnn.Close
Set rs = Nothing
Set cnn = Nothing
Set ws = Nothing
End Sub |
|