我正在尝试使用VBA和ADO选项从另一个文件查询Excel文件。当我运行此代码时,它会抛出错误“无法更新,数据库或对象只读”:
Public Function fnExecuteXlQuery _
(ByVal strPath As String, _
ByVal strQuery As String) As ADODB.Recordset
Dim rs As ADODB.Recordset
Dim conStr As String
On Error GoTo ErrorHandler
conStr = "Provider=Microsoft.Jet.OLEDB.4.0; " _
& "Data Source=" & strPath & "; Extended Properties=Excel 8.0"
Set rs = New ADODB.Recordset
rs.Open strQuery, conStr, adOpenDynamic
Set fnExecuteXlQuery = rs
Exit Function
ErrorHandler:
Set fnExecuteXlQuery = Nothing
fnDisplayError Error(Err) & "Unable to fetch data from DTS...", ERROR_TYPE_ERROR
End Function
“ strPath ”是源Excel文件,“ strquery ”具有以下SQL代码:
Select [Activity],[Name],[Date],[Hours Spent]
from [Time sheet$]
where [Activity] = 'Billable Activities'
Order by Name,date
答案 0 :(得分:1)
也许所有评论中所说的内容都需要再次写出来,以确保您真正得到解决方案:
Option Explicit
Public Sub ConnectionToExcel()
Dim rstResult As ADODB.Recordset
Dim strConnectin As String
Dim strPath As String
Dim strSQL As String
strPath = "C:\Data\YourFile.xlsm"
strConnectin = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & strPath & "';Extended Properties=""Excel 12.0 XML;HDR=YES;IMEX=1"" "
Debug.Print strConnection
strSQL = "SELECT * FROM [Time sheet$] "
Set rstResult = New ADODB.Recordset
rstResult.Open strSQL, strConnectin, adOpenForwardOnly, adLockReadOnly, adCmdText
Sheet1.Range("A1").CopyFromRecordset rstResult
End Sub
请注意,我一步一步:(1)我使用的是sub
而不是功能。 (2)select
已经简化为测试连接,可以稍后扩展。 (3)只需将结果写回第一张纸。 (4)进一步限制记录集仅限adOpenForwardOnly
和adLockReadOnly
。
此外,请注意,上述代码使用早期绑定,因此您需要在Microsoft ActiveX Data Objects 2.8 Library
- >中设置对Tools
(或更晚)的引用。 References...
。