从Excel运行Access查询的VBA

我试图运行一个VBA脚本,将运行和导出访问查询。 我能够在代码中运行查询的步骤,但是,我需要连接到DB2以在Access中运行此查询,我不知道如何实现到我的代码中input用户名和密码。

Sub RunQuery() Dim A As Object Application.DisplayAlerts = False Set A = CreateObject("Access.Application") A.Visible = False A.OpenCurrentDatabase ("J:\user\filename.mdb") A.DoCmd.OpenQuery "QueryName" A.DoCmd.ConnectString Application.DisplayAlerts = True End Sub 

代码只是停在这条线上:

 A.DoCmd.OpenQuery "QueryName" 

如果我用我的查询从这里打开我的数据库,它只是在等待我的用户名和密码。 我会尝试附上提示图片。

任何帮助将不胜感激!!

非常感谢你 在这里输入图像说明

正如瑞恩所说,使用ADO将是一个更好的select,见下文

 Public Sub RunQuery() Dim A As Object Dim rs As Object Dim strSql As String Dim strConnection As String Set A = CreateObject("ADODB.Connection") strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\user\filename.mdb" strSql = "SELECT * FROM table" A.Open strConnection Set rs = A.Execute(strSql) arr = rs.GetRows 'now the array arr has the data queried rs.Close Set rs = Nothing A.Close Set A = Nothing End Sub