Access to Excel worksheet with a password - excel

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

Related

Cant figure out how to write a connection string that allows excel to transfer data to a password protected Access

I want to send data from my excel file to access. It worked perfectly until I wanted to try and secure the database by putting a password on it. Now I just keep getting "Not a Valid Password".
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath As String
Dim pword As String
Dim strcon As String
Dim X As Long, i As Long
Dim nextrow As Long
Application.DisplayAlerts = True
'add error handling
'On Error GoTo errHandler:
'Variables for file path and last row of data
dbPath = Sheet1.Range("M5").Value
pword = "MyPassword"
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath & ";"
& _ "Jet OLEDB:Database Password=" & pword & ";"
'nextrow = Cells(Rows.Count, 1).End(xlUp).Row
'Initialise the collection class variable
Set cnn = New ADODB.Connection
'Check for data
If Sheet1.Range("B5").Value = "" Then
MsgBox " Add the data that you want to send to MS Access"
Exit Sub
End If
'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open strcon
'two primary providers used in ADO SQLOLEDB —-Microsoft.JET.OLEDB.4.0 —-
Microsoft.ACE.OLEDB.12.0
'OLE stands for Object Linking and Embedding, Database
'ADO library is equipped with a class named Recordset
Set rst = New ADODB.Recordset 'assign memory to the recordset
'ConnectionString Open '—-5 aguments—-
'Source, ActiveConnection, CursorType, LockType, Options
rst.Open Source:="Food_Deliveries", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
I have tried changing the password multiple times with no luck. The password keeps getting rejected in the code.

Excel VBA querying from Password-Protected Access Database

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

Open Connection and Recordset objects to use SQL for sheet to sheet data movement

I am trying to open Connection and Recordset to use SQL to move data between worksheets within the open workbook. To be clear all the data source sheets are open in the current workbook that I am trying to copy data from and to a different worksheet within the same open workbook.
I have used this code with different inputs to copy data from closed workbooks into the current workbook without error.
The error I am getting is the
"[Microsoft][ODBC Device Manager] Data source name not found and no
default driver specified"
.
The error occurs here:
objRecordSet.Open strSQL, objConnection, 0, 1, 1
The debugger says:
objConnection.Open is <Expression not defined in context>
objConnection.Open : <Expression not defined in context> : Empty : UserForm1.cbPrepareUpload_Click
objConnection : "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=F:\Temp04\Test.xlsm;Mode=Share Deny None;Jet OLEDB:System database="";Jet OLEDB:Registry Path="";Jet OLEDB:Database Password="";Jet OLEDB:Engine Type=35;Jet OLEDB:Database Locking Mode=0;Jet OL"
The environment is Windows 7 64 bit, Office 2010, 32 bit.
I have been agitating the little grey cells over this all day. I have tried to boil this down to the basics but now I am stuck.
Any ideas would help. Thanks, CraigM
Here is the code.
======================================================
Private Sub cbPrepareUpload_Click()
Dim HaveHeader As Boolean
Dim UseHeaderRow As Boolean
Dim i As Long
Dim RowToTest As Long
Dim mySheet As String
Dim shName As String
Dim sh As Worksheet
Dim strConnect As String
Dim strSourceRange As String
Dim strSource As String
Dim strSourceFile As String
Dim strSourceSheet As String
Dim strSQL As String
Dim strTarget As String
Dim objConnection As ADODB.Connection
Dim objRecordSet As ADODB.Recordset
Dim wksName As Worksheet
Set objConnection = New ADODB.Connection
Set objRecordSet = New ADODB.Recordset
strSourceFile = "F:\Temp04\Pricing.xlsx"
strSourceSheet = "Pricing"
strSQL = "SELECT * FROM [Sheet$3] & ;"
HaveHeader = True
UseHeaderRow = True
strSource = "Pricing"
strTarget = "BF_Upload"
For Each wksName In Sheets
If wksName.Name = strTarget Or wksName.Name Like strTarget & "*" Then i = i + 1
Next
If i = 0 Then
Else
Worksheets(strTarget).Activate
ActiveSheet.Name = strTarget & "-" & (i + 1)
End If
Worksheets.Add(Before:=Worksheets(Worksheets.Count)).Name = strTarget
ActiveSheet.Name = strTarget
Sheets(strTarget).Move Before:=Sheets(1)
strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0;HDR=Yes"";"
objConnection.Open strConnect
objRecordSet.Open strSQL, objConnection, 0, 1, 1
Sheets(strSource).Cells(2, 1).CopyFromRecordset objRecordSet
objRecordSet.Close
objConnection.Close
Worksheets(strTarget).Activate
End Sub
Is the "strConnect" parameter intentionally commented out in objConnection.Open 'strConnect Uncomment that parameter and things will hopefully work
edit: also strSQL = "SELECT * FROM [Sheet$3] & ;" is wrong. It should be strSQL = "SELECT * FROM [Sheet3$];" (the $ sign was in the wrong place and there was a stray & symbol in there too)

Using EXCEL as datasource through Microsoft OLE DB provider

We are frequently using some Excel files as a datasource for massive imports in our database. At the code level, we always refer to the corresponding data source as:
set rs = New ADODB.recordset
rs.open "SELECT * FROM [sheet1$]", myConnectionString, etc
Of course, this procedure only works when there's a sheet in the Excel file which is named [sheet1]. I'd like to add some sheet management code here, but without having to create an instance of the original Excel file, opening it, and so on (my users might get a file with a different sheet name, and might not have Excel installed).
Any idea?
You can open a recordset with the ADO OpenSchema method and then list the table (sheet) names in your workbook.
Public Sub SheetsInWorkbook()
Dim strConnect As String
Dim cn As Object
Dim rs As Object
Dim strPath As String
strPath = CurrentProject.Path & Chr(92) & "temp.xls"
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source='" & strPath & "';" _
& "Extended Properties='Excel 8.0';"
Set cn = CreateObject("ADODB.Connection")
cn.ConnectionString = strConnect
cn.Open
Set rs = cn.OpenSchema(20) '20 = adSchemaTables '
Debug.Print "TABLE_NAME"
Do While Not rs.EOF
Debug.Print rs!TABLE_NAME
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

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