2017-08-08 74 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

相關問題