Excel VBA从MS Access 2003执行存储的UNION查询

时间:2015-12-21 22:31:53

标签: vba excel-vba ms-access union ado

我正在Excel VBA中编写一个函数来对使用MS Access 2003创建的数据库执行存储查询。当存储的查询是简单查询时,代码可以工作,但如果查询是{{1 }}。例如,我使用以下代码执行存储的查询:

UNION

如果Public Function QueryDB() Dim cn As Object Dim strConnection As String Set cn = CreateObject("ADODB.Connection") ' Hard code database location and name strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server1\myDatabase.mdb" ' Open the db connection cn.Open strConnection ' Create call to stored procedure on access DB Dim cmd As Object Set cmd = CreateObject("ADODB.Command") cmd.CommandType = adCmdStoredProc cmd.CommandText = "testQuery" cmd.ActiveConnection = cn ' Execute stored query Dim rs As ADODB.Recordset Set rs = cmd.Execute() MsgBox rs.Fields(0) ' prints as expected QueryDB2 = rs.Fields(0) ' close connections rs.Close Set rs = Nothing cn.Close Set cn = Nothing End Function 是简单查询(例如,不使用testQuery),则会按预期返回数据。但是,如果UNION包含testQuery,则Excel VBA代码将失败(并且不会返回特定错误)。我该如何解决这个问题?我想避免在VBA中编写SQL语句。

2 个答案:

答案 0 :(得分:1)

考虑使用ADO的Open Recordset方法。通常,Execute用于操作命令(追加/更新/删除,存储过程等)。此外,如果Execute返回一个记录集,它只是一个仅向前(即没有游标的快照),只有MoveNextRecordCountUpdate的设施的只读记录集。 / p>

Dim cn As Object
Dim rst As Object

Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")

' Hard code database location and name
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server1\myDatabase.mdb"

' Open the db connection
cn.Open strConnection
' Open the recordset
rst.Open "testQuery", cn

Sheets(1).Range("A2").CopyFromRecordset rst

' Close recordset and db connection
rst.Close
cn.Close

答案 1 :(得分:1)

你还在苦苦挣扎吗?尝试使用ODBC查询。请按照此处列出的步骤进行操作。

http://translate.google.pl/translate?js=n&prev=_t&hl=pl&ie=UTF-8&layout=2&eotf=1&sl=pl&tl=en&u=http%3A%2F%2Fafin.net%2FKsiazkaSQLwExcelu%2FGraficznyEdytorZapytanSqlNaPrzykladzieMsQuery.htm

确保您的Union中没有空值,如果这样做,则必须使用NZ函数将空值转换为零。

相关问题