此问题是问题37339682的延续:Connecting Excel VBA to oracle DB using 'ODBC'
在上述问题中,有逐步指南将Excel连接到ODBC。 (Oracle数据库)我已成功连接到Oracle数据库并检索了表。
我的问题是: (1)如何编写Excel VBA代码,以便它可以从单元格读取SQL查询,并在表中返回SQL查询结果。我想我需要在Excel VBA代码中设置一个“数据库对象”。
(2)如果要在Microsoft Access中执行这样的代码。会有什么不同?
答案 0 :(得分:0)
不是数据库对象,而是记录集对象
Sub Example
Dim rs as New Recordset 'the new is important
Dim Conn as New Connection
Conn.connectionstring = "whatever"
'参见此处https://www.connectionstrings.com/microsoft-odbc-for-oracle/
Conn.open
Dim sql as string
sql = "whatever" 'could be text in cell ie sql = range("g1").text
rs.open sql,conn
if not rs.eof then 'if there's any data then
Activesheet.range("a2").copyfromrecordset rs 'puts data into cell
End If
rs.close
conn.close
end sub