我有一个类ADOConnector
,用于创建与工作簿的ADODB连接并查询工作簿:
Private objconnection As New ADODB.Connection
Sub connect(workbookPath As String)
On Error GoTo errHandler
objconnection.CommandTimeout = 99999999
objconnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & workbookPath & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"
Exit Sub
errHandler:
Err.Raise Err.Number, "ADOConnector.connect", Err.Description & _
" (" & workbookPath & ")"
End Sub
Function WorksheetQuery(selectSQL As String) As ADODB.Recordset
Dim objrecordset As New ADODB.Recordset
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
objrecordset.Open selectSQL, _
objconnection, adOpenStatic, adLockOptimistic, adCmdText
If objrecordset.EOF Then
Set WorksheetQuery = Nothing
Exit Function
End If
Set WorksheetQuery = objrecordset
Exit Function
errHandler:
Err.Raise Err.Number, "ADOConnector.WorksheetQuery", Err.Description
Set WorksheetQuery = Nothing
End Function
我有WorksheetQuery
的测试方法:
Sub testADOcon()
Dim ac As New ADOConnector
Dim bkPath as string
bkPath = "U:\testFolder\testWorkbook.xlsx"
ac.connect bkPath
Dim rs As ADODB.Recordset
Set rs = ac.WorksheetQuery("select distinct * from [report$]")
End Sub
这种方法给出了奇怪的不一致结果:
bkPath
处的工作簿已打开,则会因此错误而失败:The connection for viewing your linked Microsoft Excel worksheet was lost.
bkPath
处的工作簿已关闭,则会成功执行。bkPath
设置为bkPath = ThisWorkbook.FullName
,则会成功执行。"select * from [report$]"
,则无论工作簿是打开还是关闭,它都会成功执行。如何在另一个打开的工作簿上使用distinct
?