2017-08-08 56 views
0

我的数据库访问总是在一个不同的路径,但在我的woorkbook相同的文件夹。如何在当前目录中创建我的数据源?

Private Sub CommandButton14_Click() 

    Dim cn As Object 
    Dim rs As Object 
    Dim strSql As String 
    Dim strConnection As String 
    Set cn = CreateObject("ADODB.Connection") 

    'here I want to use current directory as path for my mdb 
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
     "Data Source=D:\FicheMacro\PGDB.mdb" 
    strSql = "SELECT Count(*) FROM AQ_DGE_MOD;" 
    cn.Open strConnection 
    Set rs = cn.Execute(strSql) 
    MsgBox rs.Fields(0) & " rows in MyTable" 
    rs.Close 
    Set rs = Nothing 
    cn.Close 
    Set cn = Nothing 

End Sub 
+0

我对连接不熟悉,但[this](https://stackoverflow.com/a/2814014/1726522)可能会有所帮助。 – CMArg

回答

2

正如在评论中所说,我不熟悉连接。但类似以下的东西可能会起作用。

'insert this two lines in your code 
Dim folderPath As String 
folderPath = Application.ActiveWorkbook.Path 

'change strConnection to the following 
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & folderPath & "\PGDB.mdb" 
+0

谢谢你工作得很好! –

+0

很高兴帮助:)! – CMArg

相关问题