Export Specific Cells From Excel To MS Access - excel

The code below (given to me) works but I don’t understand the Values (line line 9). I keep getting error messages when I try to add more cells. Im new to VBA could someone add more fields so I can better understand, such as:
C5 into Ingredient2
C6 into Ingredient3
C7 into Ingredient4
L5 into Lot2
L6 into Lot3
L7 into Lot4
and a whole bunch more.
The values below are arbitrary just for testing. Please tack a look at my spreadsheet
The spreadsheet I am using is here: https://mega.co.nz/#!2cZ3kKAZ!BL-HJM...1tZewrw-CH-1Dc
Sub Button10_Click()
Dim strSQL As String
Set appAccess = CreateObject("Access.Application")
appAccess.Visible = False
strSQL = "INSERT INTO [Finished Batches] ([Production Date],[Lot_Number],[Ingredient1],[Amount1]) " & _
"VALUES (#" & Range("C5") & "#,'" & Range("D5") & "','" & Range("F23") & _
"'," & Range("G23") & ")"
With appAccess
.OpenCurrentDatabase ("C:\users\jay neuh\desktop\database\ss database.mdb")
.DoCmd.RunSQL strSQL, dbFailOnError
.CloseCurrentDatabase
End With
Set appAccess = Nothing
End Sub
Thanks for any help

Access is using a SQL language to handle data, in this case an INSERT command.
An INSERT commands looks like this:
INSERT INTO [my_table_name] ([my_string_column],[my_number_column],[my_date_column])
VALUES ('my text value', 42, #2015-01-31#)
Notice a few things:
the number of columns must be the same as number of values
if you are passing text, it needes to be wrapped in single quotes
if you are passing a date, it needs to be wrapped in hash signs
if you are passing a number, it must not be wrapped
You didn't mention what kind of error you were getting, but if in your Access database the field [Lot_Number] is actually of a numeric type, wrapping it in single quotas like in your example could be the problem.
You should check Introduction to Access SQL
EDIT: You should always use
Debug.Print strSQL
to preview your SQL statement, you'll be more likely to spot if you have a syntax error somewhere in the code, like a missing comma, single quote or a bracket.

Related

What are the differences from an Oracle12C query and an Access one?

If I have to run an Oracle12C query from Excel, I cannot write it anymore as I would write it in Access. And yet it would make sense to write it into Excel, because I could launch it directly from a VBA module, without having to copy paste between files.
The query remains mostly the same, a part few modifications:
Access uses the notation collection_table.column. Change it into collection.table.column
Access names aliases table as tbl: remove them (or put table "tbl")
Access uses square brackets: remove them (in case of spaces within names, put double quotes)
Access accepts a date like #11/22/2020#. Change it into TO_DATE('11/22/2020','mm/dd/yyyy')
Access has IIf(condition1,true,IIf(condition2,... . Use CASE WHEN condition1 THEN true WHEN...
Below an example of code:
(copy in a new module, go in Tools, References... and check Microsoft ActiveX Data Object 6.1. You need to have a DSN defined in your ODBC connections: its name, username and password are here marked XXXX)
Dim Conn As New ADODB.Connection
Dim recset As New ADODB.Recordset
Dim sqlQry As String
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Data")
sqlQry = "SELECT CASE WHEN CLL1.TBL1.CNY_CD IN ('CH','DE') THEN 'GERMANY' WHEN CLL1.TBL1.CNY_CD IN ('BE','FR') THEN 'WEST' END, " _
& "CLL2.TBL2.WND_DATE, ROUND(AVG(ELEM1 + ELEM2),0) " _
& "FROM CLL2.TBL3 INNER JOIN (CLL2.TBL2 INNER JOIN CLL1.TBL1 ON CLL2.TBL2.CTR_NR = CLL1.TBL1.OGZ_NR) ON CLL3.TBL3.OGZ_NR = CLL1.TBL1.OGZ_NR " _
& "WHERE ((CLL3.TBL3 = PLN_DATE - 364) AND (ELEM3 = '0')) " _
& "GROUP BY CASE WHEN CLL1.TBL1.CNY_CD IN ('CH','DE') THEN 'GERMANY' WHEN CLL1.TBL1.CNY_CD IN ('BE','FR') THEN 'WEST' END, CLL2.TBL2.WND_DATE " _
& "HAVING ((CLL1.TBL1.CNY_CD In ('BE','CH','DE','FR')) AND (CLL2.TBL2.WND_DATE Between TO_DATE('10/3/2020','mm/dd/yyyy') AND TO_DATE('1/2/2021','mm/dd/yyyy')))"
Conn.ConnectionString = "DSN=XXXX;UID=XXXX;PWD=XXXX;": Conn.CommandTimeout = 0
Conn.Open
recset.Open sqlQry, Conn
ws.Range(ws.Cells(2, 1), ws.Cells(ws.Cells(2, 1).End(xlDown).Row, 9)).ClearContents 'delete previous data
ws.Cells(2, 1).CopyFromRecordset recset 'copy data starting from cell A2
recset.Close: Conn.Close
In this case, the functions TRIM, ROUND, AVG, and MAX had the same syntax both in Access and in Oracle.

Exporting MS Access 2016 form with empty fields to an Excel spreadsheet using SQL

I am exporting MS Access 2016 form data to an Excel spreadsheet.
Dim ctrlForm As Control
Dim sqlSelect As String
sqlSelect = "Select "
For Each ctrlForm In Forms![Student Listing].Form.Controls
If TypeOf ctrlForm Is TextBox Then
If ctrlForm .ColumnHidden = False Then
' this prints 109, which is text box - perfect
Debug.Print "Control Type: " & ctrlForm .ControlType
sqlSelect = sqlSelect & ctrlForm .Name & ","
End If 'end if for hidden
End If 'end if for TypeOf
Next ctrlForm
sqlSelect = Left(sqlSelect, Len(sqlSelect) - 1)
sqlSelect = sqlSelect & " From " & Forms![Student Listing].Form.RecordSource
'prints the SQL statement - perfect too, all the view-able fields
Debug.Print "SQL Prompt: " & sqlSelect
Dim rs As Recordset
'errors here with: Run-time error '3061' Too few parameters.
'Expected 1(or some other number) - even if there are 30 entries in the sqlSelect variable.
Set rs = CurrentDb.OpenRecordset(sqlSelect)
If I hide all fields which may contain 'no data - or empty', it works. The biggest issue is the middle initial, but I suspect looking for null/empty is the key. How do I go about doing that and keep the empty field(column) for the exported Excel file?
"Too few parameters" means you have a field name specified, with no value (even an empty one - in this case, not enough commas in the data part of the string)
option 1: your only fault may be the space inbetween "ctrlForm .Name"
if that doesn't fix it, try:
a test if the control text is empty - when it is, write out an empty string (or an error message) and a comma, not skip the field.
so after the debug:
if .Name <> "" then
sqlSelect = sqlSelect & ctrlForm .Name & ","
else
sqlSelect = sqlSelect & ","
end if
Thank you for all of your help. I found the issue. The issue turned out to be date fields. If I don't 'export' a date field, everything works. If a date field is exported - the error message I described above. Apparently, this is actually a known thing. The work around is to create a secondary 'text' field that contains the text of the date field. Export that field instead. No loss of functionality, but the export works fine.

VBA Reading Cell Value As Variable Definition Rather Than Text

My coworkers often have to send out invites for interviews (up to dozens at a time). I am writing a macro to help them autogenerate Outlook meeting invites based on all of the interviewees' information, which we store in an Excel data file.
E.g., "Dear [INSERT NAME], We would like to invite you to an interview about [INSERT SUBJECT] on [INSERT DATE]. Please call into the interview using [INSERT PHONE NUMBER] and be prepared to talk about patients with [INSERT CONDITION]."
Because my coworkers do not know VBA I'm trying to have them write it in an input sheet and have the program read it and the formatting and store it in a variable called MeetingInviteBody. So I need to take a cell's value and read it as a variable definition. The problem is the entire thing is entered as a string, even if the cell's contents are part string and part reference to another variable. Is there a way to fix this?
Thank you in advance!
Addendum: I'm hoping this will clarify what I was trying to do. This was the macro I wrote as a test:
Sub MultipleDataTypeInput()
Dim FirstLineofText As Variant
Dim PhysicianName As String
PhysicianName="Dr. Smith"
FirstLineofText=Sheets("Sheet1").Cells(1,1).Value
MsgBox(Prompt:=FirstLineofText)
End Sub
I put "Dear" & PhysicianName & "," in cell A1, What I was hoping was for Excel to then read the macro as
FirstLineofText="Dear" & PhysicianName & ","
If that happened the MsgBox would say "Dear Dr. Smith,"
Instead the prompt was ""Dear " & PhysicianName & ",""
Does this make sense?
One way to do this would be to use the replace function in VBA.
However, in cell A1, write "Dear PhysicianName," and get rid of your & concatenation. (The way you wrote it would work if you were writing it strictly in VBA. The code would concatenate the values together. For example: FirstLineofText = "Dear " & PhysicianName & ",")
Sub MultipleDataTypeInput()
Dim FirstLineofText As Variant
Dim PhysicianName As String
PhysicianName="Dr. Smith"
FirstLineofText=Sheets("Sheet1").Cells(1,1).Value
FirstLineofText = Replace(FirstLineOfText,"PhysicianName",PhysicianName)
MsgBox(Prompt:=FirstLineofText)
End Sub
I suggest this way because you said the coworkers are writing their own scripts and i didn't want to suggest an entire new methodology as it may confuse you. That said, I think there are way more efficient ways to design this.
i think that you have your logic backward
you probably want this
Sub MultipleDataTypeInput()
Dim PhysicianName As String
Dim PatientName As String
PhysicianName = Sheets("Sheet1").Range("A1").Value ' this cell should hold "Dr. Smith"
PatientName = Sheets("Sheet1").Range("B1").Value
MsgBox "Dear" & PhysicianName & ", We would like to invite you to an interview about " & PatientName
End Sub

VBA obtaining a SUM of values from MS Access, returns error: No Value Given For One or More Parameter

I have the following code to retrieve a sum out of an access field.
keep getting the error "No Value Given For One or More Parameter". I'm assuming its something simple. I tried looking up the syntax and google appears to give me what i already have. Appreciate your help.
EDIT
Public Sub sum()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim countfrmdb As String
Dim currentmth As String
currentmth = Sheets("Data").Range("f3") 'this has been formatted to get the month name. e.g: Jan. Thats how its in my database.
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=data.mdb"
strSql = "SELECT SUM(field_name) As Total FROM Table_name WHERE field_month_name = " & currentmth
cn.Open strConnection
Set rs = cn.Execute(strSql)
countfrmdb = rs.Fields(0)
MsgBox (countfrmdb)
You indicated currentmth is a text value containing the current month. So when you add currentmth to the WHERE clause without enclosing it in quotes, the db engine thinks Jan is the name of a parameter instead of a text value.
Change this ...
WHERE field_month_name = " & currentmth
to this ...
WHERE field_month_name = '" & currentmth & "'"
A good way to troubleshoot these type of issues is to examine the actual text of the SQL statement you're asking Access to execute. Debug.Print is useful for that purpose.
strSql = "SELECT SUM(field_name) As Total FROM Table_name WHERE field_month_name = " & currentmth
Debug.Print strSql
You can then view the output from Debug.Print in the Immediate window. And you can copy the statement text from there and paste it into SQL View of a new Access query for testing. Or you can show us the actual statement text which is producing the error your reported.
Based off of the information found here: No value given for the required parameter I would say that your Field_Name or table_name aren't correctly spelled. You can test this by purposefully putting in the wrong field name and you will get the same error you are getting.

update and delete single access record set via excel vba

I have this tool where employee information needs to be updated. I call in the MDB data to excel in one sheet. Now I use vlookup to see what is there and change it if needed.
I have tried some tricks however some thing seems to be wrong.. please help.
Sub update()
Dim cn As Object
Dim rs As Object
Dim a As String
strFile = "D:\temp excel\EIM.mdb"
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
a = Sheet2.Range("D4")
strSQL = "SELECT * FROM EIM WHERE EIM.NBKID=" & a
rs.Open strSQL, cn
strSQL = "UPDATE EIM SET EIM.Person#=('" & Sheet2.Range("D5") & "')WHERE EIM.NBKID=('" & Sheet2.Range("D4")
cn.Execute strSQL
End Sub
In the above code the file EIM has a table called EIM with NBKID and Person# fields.
So sorry about not explaining the request clearly, I have this tool which allows people to update there information. I cannot use access to manipulate it as not all have access available and even it would be available I do not want to give them access to master database.
We have more than 500 employee's when ever some one moves out of one role to another or when someone leaves the organization. A manager has to request for hierarchy report which takes time to come.
Instead of going through that I want this tool to maintain record of all the employees, here nbkid is nothing but system id and person# is employee number or id.
I have a code to update the information however if someone needs to edit it due to some change to their role than I need another set of code.
By doing it in excel it is easy to manage - no additional training.
I have this button which should update the change made to the vaules updated in excel sheet. I dont want it to check if the record change, I just want it to use update.
When I run the above code I get error saying "No value given for one or more reqired parameters."
I agree as to the point of modifying the data in excel as opposed to directly in access however I just spotted that your SQL statement seems to be slightly wrong. Try changing
WHERE EIM.NBKID=('" & Sheet2.Range("D4")
to
WHERE EIM.NBKID=" & Sheet2.Range("D4")
Note the removal of the single quote mark as the original statement would have been seen as
WHERE EIM.NBKID=('123456
You are missing a space between the bracket and where:
strSQL = "UPDATE EIM SET EIM.Person#=('" & Sheet2.Range("D5") _
& "') WHERE EIM.NBKID=('" & Sheet2.Range("D4")
The single quotes are needed if NBKID is a text field:
WHERE EIM.NBKID=('" & Sheet2.Range("D4") & "'"
Or for a numeric field:
WHERE EIM.NBKID=(" & Sheet2.Range("D4")
I doubt that this is a date field, but if it was, it would take hash (#) delimiters.
Just as a point of efficiency, I am not sure why you actually opened the recordset at all. The cn.Execute line works very well by itself.
I would also write a function you could call and pass it parameters to, depending on what you are trying to do. If you passed in the ID, the strFileName and the strSQL, then you have an all-purpose function.
I have a prebaked SQL string somewhere on a key pair "SELECT * from tblFoo WHERE tblFoo.ixFoo = {key}". I then get the parameter and do a Replace on the strSQL to insert the key.
Sub Update(strFile as string, strKey As String, strPerson as string)
Dim cn As Object : Set cn = CreateObject("ADODB.Connection")
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";"
cn.Open strCon
strSQL = "UPDATE EIM SET EIM.Person#="{person}" WHERE EIM.NBKID={key}"
strSQL = Replace(strSQL, {person}, strPerson, 1)
strSQL = Replace(strSQL, {key}, strKey, 1)
cn.Execute strSQL
End Sub
If speed of code greater than need for speed of execution (which is what I can gather here), then this approach alleviates all the quote/doublequote confusion
I would set aside a sheet in the book that had all the strSQL statements there, if you had a few. You could even pass this in and do the replace within Excel with its much faster native execution speed.
You now have a function you can pick up and reuse. If you are serious about using VBA, reuse heavily. It saves so much time. VBA jobs tend to place a high amount of pressure on time to produce.
I presume that you have removed error trapping to save us the hassle of reading it.

Resources