I have created a userform that insert data into an Access table. while inserting data, I want to make sure that the ID inserted must exist in the Access table. I have used the DCOUNT function to do this but this is rendering a 'Type Mismatch' error. I have tried every solution found on the internet but nothing is working here. Please help!
I have modified the DCOUNT expression to put the form variable name into '', [], creating an external variable that refers to the DCOUNT function but nothing is working
Set conn = createobject("ADODB.connection")
set rs = createobject("ADODB.recordset")
strconn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data source = C:\MyPathMyDB.accdb"
qry = "select * from employee"
with rs
.adnew
if isnumeric(ManagerID) = false then
msgbox "Invalid Manager ID"
exit sub
elseif application.worksheetfunction.dcount("Employee_ID","Employee","activ='Yes' and Employee_ID='" & [EmployeeForm.ManagerID] & "'") = 0 then
msgbox "Manager does not exist"
exit sub
else
. fields("Manager_ID").value = ManagerID
end if
end with
I expect the function to determine if the Employeeform.ManagerID exist in Employee_ID. If yes, then proceed, else display error message
Since you check for the ManagerID to be numeric, I guess its value isn't text, and active is probably a boolean, and as you can access ManagerID on its own, use it as is, and the criteria could read:
"activ=True and Employee_ID=" & ManagerID & ""
Dcount (the one you're trying to use) is an Access function: the Excel one is for querying a worksheet range. you will need to query your access database to see if there's a record:
For example:
sql = "select * from employee where activ='Yes' and Employee_ID='" & _
[EmployeeForm.ManagerID] & "'"
rs.open sql, conn
If not rs.eof then
'got a match: add the new record and update to database
else
msgbox "Manager not found!"
end if
Related
I would like to search the access database with the user initials in the UserInitials column but I get the error no value given for one or more required parameters
However, if I search the database with the ID in the ID column it works perfectly fine.
Is it possible to do this? I have checked the spelling which is fine and there are no empty fields in the database itself. I have also changed and set the Primary key from ID to UserInitials but this doesn't seem to make any difference.
Many thanks.
Public Function searchDatabase()
If UserForm1.TextBox4.Value = "" Then
MsgBox "field empty"
Else
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
con.connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\MyPC\Desktop\DatabaseOne.accdb;"
'Open Db connection
con.Open
Set rs.ActiveConnection = con
rs.Open "Select * from TableUser where UserInitials= " & UserForm1.TextBox4.Text & ""
StartRow = 3
Do Until rs.EOF
'User Initials
UserForm1.TextBox1.Text = rs.Fields(1).Value
'User Full Name
UserForm1.TextBox2.Text = rs.Fields(2).Value
'User Email
UserForm1.TextBox3.Text = rs.Fields(3).Value
rs.MoveNext
StartRow = StartRow + 1
Loop
Set rs = Nothing
con.Close
Set con = Nothing
End If
End Function
You need to embed UserForm1.TextBox4.Text in quotation marks otherwise the SQL statement will not be interpreted correctly
Try
rs.open "Select * from TableUser where UserInitials= '" & UserForm1.TextBox4.Text & "'"
Further reading Quotation marks in string expressions
I'm new to VBA and am writing a macro that downloads data from Access based on a month-end date entered by the user.
Currently, I am having issues getting information to download from Access.
To be more specific: when I run the macro and enter in the month-end date, no data is downloaded but I also receive no error messages.
I have been trying different code iterations to try to get it to work. Before I was getting various error messages; now I get no error messages but no data downloads.
I was reading online that I need to use a function to get my variable from the input box (box) to work in the Access query. I am wondering if it has to do with how I have my function set up. Or is there an issue with my Access query.
Sub Expense_Download()
'
' Expense_Download Macro
'
Dim cnn As ADODB.Connection, rs As ADODB.Recordset, sQRY As String, strFilePath As String, box As Variant, myvar As Variant
strFilePath = "C:\Users\NVanWyk\Documents\Fidato\Lunch And Learn\Lunch and Learn Access DB\Nate's Expenses DB.accdb" 'Replace the ‘DatabaseFolder’ and ‘myDB.accdb’ with your DB path and DB name
Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset
box = InputBox("What month do you want expense data for? Please use the MM/DD/YYYY format.", "Expense Month?")
If Not IsDate(box) Then MsgBox "Value entered is not a valid date, please try again.", , "Input Value is Not Correct"
End
myvar = box
cnn.Open "provider = microsoft.ace.oledb.12.0;" & _
"Data Source=" & strFilePath & ";"
'have to indent the data source or the code does not run
sQRY = "SELECT * FROM Expenses Where Expenses.Expense_Month=myvar()" 'Replace ‘tblData’ with your Access DB Table name or Query name from which you want to download the data"
rs.CursorLocation = adUseClient
rs.Open myvar(), sQRY, cnn, adOpenStatic, adLockReadOnly
Application.ScreenUpdating = False
Sheet1.Range("A2").CopyFromRecordset rs
'sheet 1 for whatever reason still pastes to the "expense" sheet
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
First of all, the line that contains the word 'End' only, will stop execution.
If you want to stop execution in case of wrong user input, do this:
If Not IsDate(box) Then
MsgBox "Value entered is not a valid date, please try again.", , "Input Value is Not Correct"
End 'or Exit Sub
End If
You store the user's month input in myvar variable but then you don't actually put into the select query.
Instead of this:
sQRY = "SELECT * FROM Expenses Where Expenses.Expense_Month=myvar()"
Try this:
sQRY = "SELECT * FROM Expenses Where Expenses.Expense_Month= " & myvar
However, the value you are expecting in InputBox is not obvious. I'm assuming that it's a number between 1 and 12 and Expense_Month field is a number too in your database.
In case it contains the year too in YYYY-MM format and is a varchar, you will need to change your code like this:
sQRY = "SELECT * FROM Expenses Where Expenses.Expense_Month= '" & myvar & "'"
Either of the above is true, IsDate is not the right function to check whether the input is correct. For example if the user types 20 into the box, it will return True as it is a date but January 20 of 1900.
Also, remove the first parameter myvar() from this line.
rs.Open myvar(), sQRY, cnn, adOpenStatic, adLockReadOnly
rs.Open sQRY, cnn, adOpenStatic, adLockReadOnly
Based on your additional input I recommend using YYYY-MM-DD as user input. So your query would be defined as:
sQRY = "SELECT * FROM Expenses Where Expenses.Expense_Month= '" & myvar & "'"
To test your query, open Locals windows in VB editor, see what the value of sQRY is once execution reaches this point and run that in Access's SQL editor to see if it is going to work.
Thanks for the help everyone!
I made the edits above and did some other research and was able to get the code to work. I think the snag was because I was using a date (MM/DD/YYYY) as the variable, I needed to add the # signs in the query so that Access recognized the variable as a date.
Sub Expense_Download()
'
' Expense_Download Macro
'
Dim cnn As ADODB.Connection, rs As ADODB.Recordset, sQRY As String, strFilePath As String, box As Variant, myvar As Variant
strFilePath = "C:\Users\NVanWyk\Documents\Fidato\Lunch And Learn\Lunch and Learn Access DB\Nate's Expenses DB.accdb" 'Replace the ‘DatabaseFolder’ and ‘myDB.accdb’ with your DB path and DB name
Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset
box = InputBox("What month do you want expense data for? Please use the MM/DD/YYYY format.", "Expense Month?")
If Not IsDate(box) Then
MsgBox "Value entered is not a valid date, please try again.", , "Input Value is Not Correct"
End
End If
myvar = box
cnn.Open "provider = microsoft.ace.oledb.12.0;" & _
"Data Source=" & strFilePath & ";"
'have to indent the data source or the code does not run
sQRY = "SELECT * FROM Expenses Where Expenses.Expense_Month= #" & myvar & "#" 'Replace ‘tblData’ with your Access DB Table name or Query name from which you want to download the data"
' access query
' # before and after the "myvar" variable are necessary for access to recognize the variable as a date and to run the query successfully.
rs.CursorLocation = adUseClient
rs.Open sQRY, cnn, adOpenStatic, adLockReadOnly
Application.ScreenUpdating = False
Sheet1.Range("A2").CopyFromRecordset rs
'sheet 1 for whatever reason still pastes to the "expense" sheet
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
In excel I have a linked table to a access table "tbl_Output"
Currently there is a manual step that before I run a excel macro I have to go into the database and open up a create table query and manual enter a criteria and run. Call it Field "Vendor Name"
This vendor name exists in the excel document. Is it possible to declare that variable in excel, pass it to access and run the create table query using that variable as its criteria.
The task gets run for many vendors so if I can automate this step I can create a loop to go through all vendors.
I have tried a workaround by having a linked pivot table to the data source that the create table query is based off then filtering in the excel pivot table itself but due to the large amount of data the refresh takes too long.
Apologies if this is something obvious. Coding vba with access is something im not familiar with.
Not 100% on the question that is being asked but I'm gonna take a shot at it. The code below will take a list of Vendor Names [Vendor Ids] and will loop through the list executing a create table query for each of the Vendor Ids that contains the information for that specific Vendor
Sub umCreateDBTables()
Dim DBPath As String ' Path to the database with the information
Dim DBPath2 As String ' Path to the database to store the newly created tables in
Dim xlCell As Range
Dim sSQL As String
Dim DB As DAO.Database
Dim VenID As String
Dim i As Integer
DBPath = "C:\DB_Temp\AccessDB_A.accdb"
DBPath2 = "C:\DB_Temp\AccessDB_B.accdb"
Set DB = OpenDatabase(DBPath, True, False)
Set xlCell = Range("A2") ' Assumes that this is the beginning of the column with your vendor ids
Do Until xlCell.Value = "" ' Loops through the list of vendor ids until it gets to an empty cell
VenID = "v_" & xlCell.Value ' would be best to feed this through a function to strip out any invalid db field name characters
sSQL = "SELECT T1.F1, T1.F2, T1.F3, INTO " & VenID & " IN '" & DBPath2 & "' FROM T1 WHERE (((T1.F1)='" & xlCell.Value & "'));"
For i = DB.TableDefs.Count - 1 To 0 Step -1 ' Cycle through the list of database objects [tables, queries, etc....]
If DB.TableDefs(i).Name = VenID Then ' If the vendor table already exists in the DB, delete it so it can be recreated
DB.TableDefs.Delete (VenID)
End Select
Next i
DB.Execute sSQL ' Run the SQL to create the vendor table
Set xlCell = xlCell.Offset(1, 0) ' move down to the next row
Loop
DB.Close
Set DB = Nothing
Set xlCell = Nothing
End Sub
Hope this helps
Thank you so much Glenn G
The code you provided was extremely helpful and put me in the right direction.
I was having run-time issues with the DAO even with references added though but worked around it.
Code I got to work was:
Sub UpdateDatabase()
Dim DBPath As String
Dim xlcell As Range
Dim sSQL As String, stProvider As String
Dim DB As New ADODB.Connection
DBPath = "C:\Temp\Data.accdb"
stProvider = "Microsoft.ACE.OLEDB.12.0"
With DB
.ConnectionString = DBPath
.Provider = stProvider
.Open
End With
Set xlcell = Sheet3.Range("X2")
Do Until xlcell.Value = ""
venid = xlcell.Value
sSQL = "SELECT ALL * INTO tbl_Output FROM qry_Data WHERE (((qry_Data.VendorName)='" & xlcell.Value & "'));"
DB.Execute "DROP TABLE tbl_Output;"
DB.Execute sSQL
Set xlcell = xlcell.Offset(1, 0)
Loop
DB.Close
Set DB = Nothing
Set xlcell = Nothing
Thank you again for your help.
Regards
Richard
I am having trouble getting data from an Access Database. I found this code online, and it seems to work (to an extent), but for some reason it will only pull the column headers, and none of the data from the query. I am not too familiar with Access, that is why I pulled one from offline.
Someone had a similar post a while back, where the code they used was the same, and our queries were exactly the same, but we had different issues.
Importing Data From Access Using Excel VBA
Would anyone happen to know why the data won't pull?
Sub getDataFromAccess()
Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer
Dim startdt As String
Dim stopdt As String
Dim refresh
refresh = MsgBox("Start New Query?", vbYesNo)
If refresh = vbYes Then
Sheet1.Cells.Clear
startdt = Application.InputBox("Please Input Start Date for Query (MM/DD/YYYY): ", "Start Date")
stopdt = Application.InputBox("Please Input Stop Date for Query (MM/DD/YYYY): ", "Stop Date")
DBFullName = "X:\MyDocuments\CMS\CMS Database.mdb"
' Open the connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Connect
Set Recordset = New ADODB.Recordset
With Recordset
Source = "SELECT * FROM Tracking WHERE [Date_Logged] BETWEEN " & startdt & " AND " & stopdt & " ORDER BY [Date_Logged]"
.Open Source:=Source, ActiveConnection:=Connection
For Col = 0 To Recordset.Fields.Count - 1
Range(“A1”).Offset(0, Col).Value = Recordset.Fields(Col).Name
Next
Range(“A1”).Offset(1, 0).CopyFromRecordset Recordset
End With
ActiveSheet.Columns.AutoFit
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub
An easy way to get data in Excel, especially from Access, is to use the menu "Data > Access". This creates a connection to a table, that you can freely edit.
At the very least, that is a convenient way to limit your investigations to:
the query you typed (the connection string will always be OK, so if you're getting no values, it comes from the query)
or the VBA itself (if the table is returning values but not the corresponding VBA Sub, then you know it comes from the VBA itself, not the SQL).
I'm skipping the creation of connection becuse it's really straightforward; it's better to focus on what you can do once the table has been created.
Edit the connection
When you select the table and go to menu "Data > Properties", then in the window you click on the top right button "Connection properties", you get to the definition of the connection, i.e. some properties in the first tab and the actual definition in the second tab.
If you move the .mdb file, you'll have to change the connection string accordingly. There should be no other events forcing you to alter it.
If you want to type an actual complex query, you'll need to:
Change the command type from "Table" to "SQL"
Type the query in the bottom edit box.
Note if you want to define dynamic parameters in the WHERE clause, you can put question marks (?) instead of hardcoded values. Question marks can be linked to either constants (with a prompt to change their values) or cell.
Use in VBA
Once you checked with the connection that everything works, you have 2 solutions to put that in VBA.
Either use exactly the code you have above; in that case, you can make things easy by simply copying the connection string and the query.
Alternatively and this is what I would recommend, the table we have built previously can be updated very easily in VBA.
Use this piece of code:
WorksheetWithTable.ListObjects(1).QueryTable.Refresh
You really don't need more than this 1 line of code to do the refresh.
If you set your query to automatically refresh when a cell's value is being modified, then you do not even need it at all.
Note #1: Instead of an index in .ListObjects(1), you can use the table name.
Node #2: Refresh has an optional parameters to drive if the query is to be refresh in the background. True means the VBA code will not wait for the execution to end before moving to the next instruction. False, obviously, is the opposite.
The posted code is missing End If line. Perhaps this is just a posting typo because code should not compile and run.
The query SQL needs # delimiters for the date parameters:
Source = "SELECT * FROM Tracking WHERE [Date_Logged] BETWEEN #" & startdt & "# AND #" & stopdt & "# ORDER BY [Date_Logged]"
Text field would need apostrophe delimiters. Number field does not need delimiters.
I solved the answer to my own question after hours, i found a different set of code that worked fine. Thank you all for your help!
Sub getdatamdb()
Dim cn As Object, rs As Object
Dim intColIndex As Integer
Dim DBFullName As String
Dim TargetRange As Range
10 DBFullName = "X:\MyDocuments\CMS\CMS Database.mdb"
20 On Error GoTo Whoa
30 Application.ScreenUpdating = False
40 Set TargetRange = Sheets("Sheet1").Range("A1")
50 Set cn = CreateObject("ADODB.Connection")
60 cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & DBFullName & ";"
70 Set rs = CreateObject("ADODB.Recordset")
80 rs.Open "SELECT * FROM Tracking WHERE [Date_Logged] BETWEEN #" & startdt & "# AND #" & stopdt & "# ORDER BY [Date_Logged]", cn, , , adCmdText
' Write the field names
90 For intColIndex = 0 To rs.Fields.Count - 1
100 TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
110 Next
' Write recordset
120 TargetRange.Offset(1, 0).CopyFromRecordset rs
LetsContinue:
130 Application.ScreenUpdating = True
140 On Error Resume Next
150 rs.Close
160 Set rs = Nothing
170 cn.Close
180 Set cn = Nothing
190 On Error GoTo 0
200 Exit Sub
Whoa:
210 MsgBox "Error Description :" & Err.Description & vbCrLf & _
"Error at line :" & Erl & vbCrLf & _
"Error Number :" & Err.Number
220 Resume LetsContinue
End If
End Sub
basically, I want to have the value of my combobox1 as a field name of my query below. can somebody help me here?
Dim db As Database
Dim rs As DAO.Recordset
Set db = OpenDatabase("\\location\file.mdb")
Set rs = db.OpenRecordset("select * from customerinfo " _
& "where '"& (combobox1.text) &"' likE '*" & (txtsearch) & "*';")
If rs.RecordCount = 0 Then
MsgBox "No Item Found"
Else
Do While Not rs.EOF = True
listbox.AddItem
On Error Resume Next
listbox.List(listbox.ListCount - 1, 0) = rs("Fieldname").Value
rs.MoveNext
Loop
end if
There is an error in your query:
where '"& (combobox1.text) &"' likE
This creates an incorrect where clause, where 'fieldname' likE, which should be where fieldname likeE. Change the query to:
where "& (combobox1.text) &" likE
Note: It is best to create the query string in a variable. That makes it easier to spot any errors.