我尝试通过VBA与我的数据库建立连接,因为使用数据透视表连接大约需要2分钟(连接和导入数据)。在另一项工作中,我用vba代码连接到数据库并执行mdx查询,这比使用excel数据透视表要快得多。在这种情况下,我无法使用mdx查询,因为它不可用(不同的数据库?)。
我找到了进行连接和查询的代码。问题是,无论是否连接,我都无法获得任何信息,查询部分给我错误:(运行时错误'-2147217865(80040e37)自动化错误)。
代码如下:
Sub SQL_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim strCon As String
'http://learnexcelmacro.com/wp/2011/11/sql-connection-string/
strCon = "Provider=SQLOLEDB.1;Data Source=sql2\bbqsrv;Initial Catalog=Reports;Integrated Security=SSPI"
'--- Open the above connection string.
con.Open (strCon)
con.CommandTimeout = 120 'sec
'--- Now connection is open and you can use queries to execute them.
'--- It will be open till you close the connection
'slq query
query = "SELECT TOP 10 * FROM [Reports]"
'Performs the actual query
rs.Open query, con
'Dumps all the results from the query into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rs
End Sub
首先,你们可以帮助我如何检查即时通讯是否正确连接并且这部分代码有效吗?在Excel中,如果我签入DATA> Connections,则什么也没有。 其次,如果我只有数据透视表访问而不是数据库/ SQL,如何编写简单查询?在这种情况下,我无法检查mdx查询。