Excel VBA querying from Password-Protected Access Database - excel

I am currently trying to query one of the table from Microsoft Access Database (.mdb), however, when I try to do a SELECT * FROM myTable, it gives an "User-defined type not defined". May I know why?
Here's my sample code:
Private Sub CommandButton1_Click()
Dim db As DAO.Database
Dim dbPath As String
Dim aQuery As String
Dim pword As String
Dim rs As DAO.Recordset
dbPath = ThisWorkBook.Path & "\Database.mdb"
pword = "password"
aQuery = "SELECT * FROM myTable"
Set db = Access.DBEngine.Workspaces(0).OpenDatabase(dbPath, True, False, ";PWD=" & pword)
Set rs = db.Execute(aQuery)
rs.MoveFirst
MsgBox rs.Fields(0)
End Sub

Using ADO
Add Reference: Microsoft ActiveX Data Objects 2.8 Library
Sub test()
Dim Conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dbPath As String
Dim aQuery As String
Dim pword As String
Dim strcon As String
dbPath = ThisWorkbook.Path & "\Database.mdb"
pword = "abcd"
aQuery = "SELECT * FROM myTable"
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & dbPath & ";" _
& "Jet OLEDB:Database Password=" & pword & ";"
Conn.Open strcon
rs.Open aQuery, Conn
If Not (rs.EOF And rs.BOF) Then
MsgBox rs.Fields(0)
End If
rs.Close
Set rs = Nothing
Set Conn = Nothing
End Sub
Using DAO
Add Reference: Microsoft DAO 3.6 Object Library
As #Tim highlighted you have missed adding the reference to library.
Sub test()
Dim db As DAO.Database
Dim dbPath As String
Dim aQuery As String
Dim pword As String
Dim rs As DAO.Recordset
dbPath = ThisWorkbook.Path & "\Database.mdb"
pword = "abcd"
aQuery = "SELECT * FROM myTable"
Set db = OpenDatabase(dbPath, True, False, ";PWD=" & pword)
Set rs = db.OpenRecordset(aQuery)
rs.MoveFirst
MsgBox rs.Fields(0)
End Sub

try this:
Private Sub CommandButton1_Click()
Dim db As object, rs as object
Dim dbPath As String
Dim aQuery As String
Dim pword As String, uid as string
dbPath = ThisWorkBook.Path & "\Database.mdb"
pword = "password"
uid = "myid"
set db = createobject("adodb.connection")
with db.open
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath & _
";User ID=" & uid & ";Jet OLEDB:Database Password=""" & pword & """;"
end with
aQuery = "SELECT * FROM myTable"
Set rs = db.Execute(aQuery)
rs.MoveFirst
MsgBox rs.Fields(0)
db.close
set rs = nothing
set db = nothing
End Sub

Related

executing SQL in workbook

I am unable to execute a simple sql statement. - sorry I am sure this is simple and I am missing something small. Error says missing the object.
dbPath = "C:\Users\User\Documents\test0419.accdb"
tblName = "Wait_Data_Table"
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & dbPath & "';"
conn.Open strcon
Set wrkSpaceNew = DBEngine.CreateWorkspace("Check", "admin", "", dbUseJet)
rcdDetail = ("SELECT order.ord_id, order.job_id, order.bc_desc, order.ord_amount, order.ord_diff FROM Order")
Set rs = DBEngine.BeginTrans(rcdDetail)
You can use either DAO or ADODB, not normally both. See difference-between-ado-and-dao
Option Explicit
Sub UseDAO()
Const SQL = " SELECT order.ord_id, order.job_id, order.bc_desc, " & _
" order.ord_amount, order.ord_diff " & _
" FROM [Order]"
Const dbpath = "C:\Users\User\Documents\test0419.accdb"
Dim wkspace As workspace, db As DAO.Database, rs As DAO.Recordset
Set wkspace = DBEngine.CreateWorkspace("Check", "admin", "", dbUseJet)
Set db = wkspace.OpenDatabase(dbpath)
Set rs = db.OpenRecordset(SQL)
Sheet1.Range("A1").CopyFromRecordset rs
db.Close
Set db = Nothing
wkspace.Close
Set wkspace = Nothing
MsgBox "Results on sheet " & Sheet1.Name, vbInformation, "DAO"
End Sub
Sub UseADODB()
Const SQL = " SELECT order.ord_id, order.job_id, order.bc_desc, " & _
" order.ord_amount, order.ord_diff " & _
" FROM [Order]"
Const dbpath = "C:\Users\User\Documents\test0419.accdb"
Dim strConn As String, conn As ADODB.Connection, rs As ADODB.Recordset
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & dbpath & "';"
Set conn = New ADODB.Connection
conn.Open strConn
Set rs = conn.Execute(SQL)
Sheet1.Range("A1").CopyFromRecordset rs
conn.Close
MsgBox "Results on sheet " & Sheet1.Name, vbInformation, "ADODB"
End Sub
Don't forget to add Activex Data Object in Reference Section
Dim baglanti As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sunucu, veritabani, id, sifre, sorgu As String
sunucu = "DESKTOP-GF32DLC\SQLEXPRESS"
veritabani = "AdventureWorks2014"
id = ""
sifre = ""
sorgu = "SELECT * FROM [HumanResources].[Department] Where [GroupName]='Manufacturing'"
baglanti.Open "Driver={SQL SERVER};Server=" & sunucu & ";Database=" & veritabani & _
";Uid=" & id & ";Pwd=" & sifre & ";"
rs.Open sorgu, baglanti, adOpenStatic
With Range("A1:AA1000")
.ClearContents
.CopyFromRecordset rs
End With
rs.Close
baglanti.Close
This way you can make a healthy sql connection.
I used to use it to connect sql in the past

Access to Excel worksheet with a password

I created an Excel file with 3 worksheets like this:
My goal is: making the worksheets accessible only with a password. That means you can see the content of the worksheet only with a password.
For Example: When the "User" clicks on "Admin", the content of the worksheet is only visible after entering the right password.
Worksheet protect is useless.
Is it possible ?
There is no possibility to securely protect one sheet only from viewing. You can only protect a whole workbook from viewing (with password).
Any workaround you try to securely hide/protect a sheet with password can easily be tricked out by any user.
The only way to securely hide data from users is not to hand out this data at all. The only really secure way is to have something like a client server process where the server has the raw data, the client sends a request to that server, and the server only sends the data the user is allowed to see.
Try following codes.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim MySheetName As String
MySheetName = "Admin1" 'The sheed name which you want to hide.
If Application.ActiveSheet.Name = MySheetName Then
Application.EnableEvents = False
Application.ActiveSheet.Visible = False
response = Application.InputBox("Password", "Enter Password", , Type:=2)
If response = "rainy2019" Then 'Unhide Password.
Application.Sheets(MySheetName).Visible = True
Application.Sheets(MySheetName).Select
End If
End If
Application.Sheets(MySheetName).Visible = True
Application.EnableEvents = True
End Sub
VBA Window:
How about this ADO solution?!
Add Reference: Microsoft ActiveX Data Objects 2.8 Library
Sub test()
Dim Conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dbPath As String
Dim aQuery As String
Dim pword As String
Dim strcon As String
dbPath = ThisWorkbook.Path & "\Database.mdb"
pword = "abcd"
aQuery = "SELECT * FROM myTable"
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & dbPath & ";" _
& "Jet OLEDB:Database Password=" & pword & ";"
Conn.Open strcon
rs.Open aQuery, Conn
If Not (rs.EOF And rs.BOF) Then
MsgBox rs.Fields(0)
End If
rs.Close
Set rs = Nothing
Set Conn = Nothing
End Sub
Or, use a DAO solution.
Add Reference: Microsoft DAO 3.6 Object Library
Sub test()
Dim Conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dbPath As String
Dim aQuery As String
Dim pword As String
Dim strcon As String
dbPath = ThisWorkbook.Path & "\Database.mdb"
pword = "abcd"
aQuery = "SELECT * FROM myTable"
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=" & dbPath & ";" _
& "Jet OLEDB:Database Password=" & pword & ";"
Conn.Open strcon
rs.Open aQuery, Conn
If Not (rs.EOF And rs.BOF) Then
MsgBox rs.Fields(0)
End If
rs.Close
Set rs = Nothing
Set Conn = Nothing
End Sub

How to set connection string in excel to import data from sql?

I want to import data from 2 columns in SQL server, im following this code from http://buffalobi.com/excel/excel-vba-import-sql-server-data/, whats wrong?
Private Sub CommandButton2_Click()
Call CommandButton1_Click
Dim conn As New ADODB.Connection, cmd As New ADODB.Command, rs As New ADODB.Recordset
With conn
.ConnectionString = _
"Provider = Microsoft.ACE.OLEDB.12.0; " & _
"data source=localhost; " & _
"initial catalog=PTrails_Core_DB;" & _
"integrated security=True;"
.Open
End With
and i get this message
I would set 'ConnectionString' as variable and use that to open. If this doesn't work, it would have to be the actual link you're referring to that's causing an issue. Maybe because it's ending on semicolon.
Dim ConnectionString as String
ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;data source=localhost;initial catalog=PTrails_Core_DB;integrated security=True"
conn.Open ConnectionString
This will do what you want.
Sub ImportFromSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim RS As ADODB.Recordset
Set RS = New ADODB.Recordset
Server_Name = "your_server_name"
Database_Name = "Northwind"
'User_ID = "******"
'Password = "****"
SQLStr = "select Field1, Field2 from dbo.TBL" 'and PostingDate = '2006-06-08'"
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";"
'& ";Uid=" & User_ID & ";Pwd=" & Password & ";"
RS.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A1")
.ClearContents
.CopyFromRecordset RS
End With
RS.Close
Set RS = Nothing
Cn.Close
Set Cn = Nothing
End Sub

Run access query from Excel and pass parameters to the query

How to execute a query in MS Access db from Excel VBA code or macro.
MS-Access query accepts some parameters, that needs to be passed from Excel.
Thanks
Here is one possibility:
Dim cn As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
strFile = "C:\docs\Test.mdb"
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile
''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
strSQL = "INSERT INTO ATable (AField) " _
& "VALUES (" & Sheet1.[A1] & ")"
cn.Execute strSQL
cn.Close
Set cn = Nothing
You can also refer in-line in the sql to a dataset from Excel.
EDIT re comments
Using a command:
strSQL = "SELECT * FROM ATable " _
& "WHERE AField = #AField"
With cmd
Set .ActiveConnection = cn
.CommandText = strSQL
.CommandType = 1 'adCmdText
''ADO Datatypes are often very particular
''adSmallInt = 2 ; adParamInput = 1
.Parameters.Append .CreateParameter("#AField", 2, 1, , Sheet1.[A1])
End With
Set rs = cmd.Execute
See also: http://support.microsoft.com/kb/181782
This uses ADODB.
Set m_Connection = New Connection
If Application.Version = "12.0" Then
m_Connection.Provider = "Microsoft.ACE.OLEDB.12.0"
Else
m_Connection.Provider = "Microsoft.Jet.OLEDB.4.0"
End If
m_Connection.Open <full path to Access DB>
If m_Connection.State > 0 Then
Dim rsSource As New Recordset
rsSource.Open strQuery, m_Connection, adOpenForwardOnly, adLockReadOnly
Dim result As Long
Dim rngTarget As Range
rngTarget = ThisWorkbook.Worksheets(m_SheetName).Range("A1")
If Not rsSource.BOF Then
result = rngTarget.CopyFromRecordset(rsSource)
End If
If rsSource.State Then rsSource.Close
Set rsSource = Nothing
End If
So it runs the query and puts it where you like. strQuery is the name of a query in the db or an SQL string.

Copy from Recordset into a new Workbook created on the fly

I wanted to create a recordset with data in my workbook. Then drop that recordset into a new workbook I created. Am I barking up the wrong tree here, is it not possible because the recordset is out of scope of the new workbook? Help please?
Sub CopyWithADODB()
' Reference to: Microsoft ActiveX Data Objects 6.1 Library
Dim myConnection As String
Dim RS As ADODB.Recordset
Dim mySQL As String
Dim strPath As String
Dim wsTarget As Worksheet
Dim wbTarget As Workbook
Dim con As ADODB.Connection
Dim Now As String
Dim Server As String
Server = "ServerX"
Now = Date
Now = "" & Server & "_" & Format(Now, "DD-MM-YYYY")
Now = Replace(Now, "-", "_")
Application.ScreenUpdating = False
strPath = ActiveWorkbook.FullName
myConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & strPath & "';Extended Properties=""Excel 12.0 XML;HDR=YES;IMEX=1"" "
mySQL = "SELECT [d_pending$].[CustName],[d_pending$].[CustAddress] , [d_pending$].[CustTel], [d_pending$].[Email], [d_pending$].[Order], [d_pending$].[Loyalty] " & _
"FROM [d_pending$]"
Set RS = New ADODB.Recordset
RS.Open mySQL, myConnection, adOpenForwardOnly, adLockOptimistic
Set wbTarget = Workbooks.Add
wbTarget.Sheets("Sheet1").CopyFromRecordset RS
Workbooks.Add.SaveAs Filename:="" & Now & ""
wbTarget.Close SaveChanges:=False
RS.Close
Set RS = Nothing
Application.ScreenUpdating = True
End Sub

Resources