Saturday, February 18, 2012

[VBA Excel] Connect the Access database and Show the data on Output Sheet

Simple to connect as M$ Acess Database via VBA Excel code and get this to sheet and range target, the code is advantage about one function name ConAccess and you can call this function pass format below

1:  Sub Con()  
2:    Call ConAccess("SELECT * FROM JobDetail", "Sheet1", "A1")  
3:    Call ConAccess("SELECT * FROM Machine", "Sheet1", "D1")  
4:    Call ConAccess("SELECT * FROM ReqDept", "Sheet1", "F1")  
5:    Call ConAccess("SELECT * FROM ReqSection", "Sheet1", "H1")  
6:    Call ConAccess("SELECT JobNo FROM JobDetail ORDER BY JobNo DESC", "Sheet1", "J1")  
7:  End Sub  



1:  Function ConAccess(InputSQL As String, OutPutSH As String, OutputRNG As String)  
2:  Dim rsAcc As New ADODB.Recordset  
3:  Dim rs As New ADODB.Command  
4:  Dim CnnStr As String  
5:  Dim FileSource As String  
6:    FileSource = "D:\DB.mdb"  
7:    CnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & _  
8:        "Data source=" & FileSource & ";"  
9:    If OutPutSH <> "" And OutputRNG <> "" Then  
10:        rsAcc.Open InputSQL, CnnStr  
11:        Sheets(OutPutSH).Range(OutputRNG).CopyFromRecordset rsAcc  
12:        rsAcc.Close  
13:        Set rsAcc = Nothing  
14:    Else  
15:      rs.ActiveConnection = CnnStr  
16:      rs.CommandText = InputSQL  
17:      rs.Execute  
18:      Set rs = Nothing  
19:    End If  
20:  End Function  

No comments:

Post a Comment