Export Excel Spread Sheet to Access Table with A Timestamp? - sql

I currently use a set up like the one below.
Set AccessConn = CreateObject("ADODB.Connection")
sExcel = "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=" & ThisWorkbook.FullName & "].[Sheet1$]"
AccessConn.Open "DSN=Foo", "", ""
sSQL = "Insert Into BarTable Select * FROM " + sExcel
AccessConn.Execute sSQL
Now if I wanted to add a now() column in the export is this possible? something like
Set AccessConn = CreateObject("ADODB.Connection")
sExcel = "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=" & ThisWorkbook.FullName & "].[Sheet1$]"
AccessConn.Open "DSN=Foo", "", ""
sSQL = "Insert Into BarTable Select *,NOW() FROM " + sExcel
AccessConn.Execute sSQL
Where the last column in BarTable is a Date/Time column and I want to insert the current time into it?

to enter the date in SQL you may need to convert it into text - Access itself can handle 'Now()' but not sure if it can when being passed a SQL string. Something like the below should do it.
sSQL = "Insert Into BarTable Select *,#" & format(NOW(),"MM/DD/YYYY hh:mm:ss") & "# As DateTimeStamp FROM " + sExcel
In Access I have two functions that I use for getting the date or date and time stamp when building SQL strings, I haven't tested but they should translate into Excel VBA okay:
Function MakeSQLDateTime(pSourceDate As Variant) As String
Dim SQLDay As String, SQLMonth As String, SQLYear As String, SQLTime As String
SQLDay = Day(pSourceDate)
SQLMonth = Month(pSourceDate)
SQLYear = Right(Year(pSourceDate), 4)
SQLTime = Hour(pSourceDate) & ":" & Minute(pSourceDate) & ":" & Second(pSourceDate)
MakeSQLDateTime = "#" & SQLMonth & "/" & SQLDay & "/" & SQLYear & " " & SQLTime & "#"
End Function
Function MakeSQLDate(pSourceDate As Variant) As String
Dim SQLDay As String
Dim SQLMonth As String
Dim SQLYear As String
SQLDay = Day(pSourceDate)
SQLMonth = Month(pSourceDate)
SQLYear = Right(Year(pSourceDate), 4)
MakeSQLDate = "#" & SQLMonth & "/" & SQLDay & "/" & SQLYear & "#"
End Function
To use these to complete what you are trying:
sSQL = "Insert Into BarTable Select *," & makeSQLDateTime(Now()) & " As DateTimeStamp FROM " + sExcel

Related

Why does "Enter parameter value" appears using INSERT INTO VALUES?

I'm always getting the "enter parameter value error" when I try to run this code. The error refers to idPat, idSP, idPar and measure_value.
I have checked with the debug idPar, idPat, idSP and measure_value and they assume the correct value; the errors comes out when I run sql.
Dim idPar As Integer
Dim idPat As Integer
Dim idSP As Integer
Dim current_fc As String
Dim namePar As String
Dim sql As String
Dim measureValue As Integer
current_fc = TempVars!CurrentUsername
namePar = Me.cmbManualDailyPar.Value
measureValue = Me.txtMeasureValue
idPar = Nz(DLookup("ID_par", "Parameter", "name_par = '" & namePar & "'"), 0)
idPat = Nz(DLookup("ID_patient", "Patient", "fiscal_code = '" & current_fc & "'"), 0)
idSP = Nz(DLookup("ID_SP", "Diagnosis", "ID_patient = " & idPat & ""), 0)
sql = "INSERT INTO Measure(ID_par, measure_value,ID_SP,ID_patient)" & _
" VALUES(idPar,measureValue,idSP,idPat);"
DoCmd.RunSQL sql
Your VALUES part is just text. What you need is:
" VALUES(" & idPar & "," & measureValue & "," & idSP & "," & idPat & ")"
You may also need to enclose text values in database quotes, for example:
" VALUES(" & idPar & ", '" & measureValue & "'," & idSP & "," & idPat & ")"
to enclose measureValue if it is text.

Is it the same to insert into tables from query as from table using VBA?

so this is my code below it works just fine when selecting from a table :
Private Sub cmdStart_Click()
Dim strSql1 As String
Dim strSql2 As String
Dim strSql3 As String
Dim strSql4 As String
Dim qdef As DAO.QueryDef
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Set dbs = CurrentDb
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , format('" & Forms("qoyod").qaed_date & "' , 'dd/mm/yyyy') , sum(sale_bill_total), 167 " & _
"from sale_bill where sale_bill_date between format( '" & Me.cmbQFrom & "' ,'mm/dd/yyyy') and format( '" & Me.cmbQTo & "' ,'mm/dd/yyyy') and sale_bill_type = 1 "
dbs.Execute strSql1
but when I try to select from a query it just wont work
is there something am doing wrong ?
Thanks in advance.
First you'll need to enclose your data correctly:
numbers need no enclosure: 200
string need to be enclosed with ' or ": 'String' or "String"
Dates need to be enclosed with #: #2020-11-22#
When concatenating strings to an SQL string I usually use the single quotes '
So just guessing on what the field data types are, here is what you SQL string should look like:
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , #" & format(Forms("qoyod").qaed_date, "yyyy-mm-dd") & "#, sum(sale_bill_total) , 167 " & _
"from sale_bill where sale_bill_date between #" & format( Me.cmbQFrom, "yyyy-mm-dd") & "# and #" & format(Me.cmbQTo, "yyyy-mm-dd") & "# and sale_bill_type = 1"
dbs.Execute strSql1
To simplify date conversion use the ISO format yyyy-mm-dd, this will prevent any accidental switching between the day and month in certain configurations.
If you're still getting an error, then try printing the result to the Immediate Window like this for troubleshooting:
Debug.Print strSql1
dbs.Execute strSql1
before trying to execute the string.

How to use VBA variable in SQL string? Enter Parameter Value error

I get a popup box asking for the parameter value for the value of CXIid
Enter Parameter Value
for CXI00012.
I tried ' " & CXIid & " ' but then I get a result of 0 rows being updated. However when I put a value in the where clause or into the Enter Parameter Value prompt I get the correct row updated.
How do I get it to recognize CXIid as a value?
Private Sub cmdSave_Click()
Dim CXIid As String
Dim testSQL As String
CXIid = Form_sf_ParticipantView.CXI_ID
testSQL = "UPDATE [tbl_Participants]" & _
"SET tbl_Participants.Consent = (Forms.frmReturn.cboConsent.value)" & _
"WHERE ((tbl_Participants.CXI_ID = " & CXIid & " ));"
DoCmd.RunSQL testSQL
You have a few different types of mistakes... the variables cannot be within the quotes, and since the field CXI_ID is a String, it does need quotes.
This assumes that the Consent field is numeric and the combobox is returning a numeric value as well.
testSQL = "UPDATE [tbl_Participants]" & _
" SET tbl_Participants.Consent = " & Forms.frmReturn.cboConsent.value & _
" WHERE tbl_Participants.CXI_ID = '" & CXIid & "'"
Also note the spaces I added before SET and WHERE. Those are important.
Use MsgBox testSQL or Debug.Print testSQL to double check what testSQL is set to before you run it.
If the field CXI_ID is not a string but you are just using a string as the type of variable holding the value for some reason:
testSQL = "UPDATE [tbl_Participants]" & _
" SET tbl_Participants.Consent = " & Forms.frmReturn.cboConsent.value & _
" WHERE tbl_Participants.CXI_ID = " & CXIid
If they are both strings:
testSQL = "UPDATE [tbl_Participants]" & _
" SET tbl_Participants.Consent = '" & Forms.frmReturn.cboConsent.value & "'" & _
" WHERE tbl_Participants.CXI_ID = '" & CXIid & "'"

Update SQL table from VB multiple where condition

I am attempting to update an SQL table from VBA (with the below code)and cant seem to get it correct. I would like to update the columns one, two, three and four based on the search conditions of A, B, C, D, E. What am I getting wrong here? There is no error given, but the table just does not update? thank
Sub UpdateData(A As String, B As String, C As String, D As String, E As String, one As Double, two As Double, three As Double, four As Double)
Dim sA As String, sB As String, sC As String, sD As String, sDesk As String, sE As String
Dim sone As Double, stwo As Double, sthree As Double, sfour As Double
Dim objConn As ADODB.Connection
Set objConn = New ADODB.Connection
objConn.ConnectionString = "Provider=SQLOLEDB;Data Source=source;Initial Catalog=Model_table;Integrated Security=SSPI"
objConn.Open
Set objRec = New ADODB.Recordset
Date = Format(Range("date").Value, "YYYY-MM-DD")
sA = A
sB = B
sC = C
sD = D
sE = E
sone = one
stwo = two
sthree = three
sfour = four
StrSQL = "UPDATE pnl_results SET (" & sone & "," & stwo & "," & sthree & "," & sfour & ") Where ('" & date = sDate & "', '" & AA= sA & _
"','" & BB= sB & "','" CC= & sC & "','" & DD= sD & "','" & EE=sE & ")"
Set objRec = objConn.Execute(StrSQL)
objConn.Close
Set objConn = Nothing
End Sub
There are several errors in your code:
You don't need parentheses.
Put the column names directly in the string, don't surround them with apostrophes.
Surround all string values with apostrophes.
Use AND or OR operator to combine different conditions, not a comma.
Try this:
StrSQL = "UPDATE pnl_results SET " & _
" one = '" & sone & _
"', two = '" & stwo & _
"', three = '" & sthree & _
"', four = '" & sfour & _
"' Where date = '" & sDate & _
"' AND AA = '" & sA & _
"' AND BB = '" & sB & _
"' AND CC = '" & sC & _
"' AND DD = '" & sD & _
"' AND EE = '" & sE & "'"
As mentioned in the comments, using inline query with values coming directly from user input makes your code open to SQL injection attacks. Either validate user input before using it in the query, or better use a parameterized query.
You are confusing the syntax between an Update and an Insert Into. It should look more like this:
StrSQL = "UPDATE pnl_results SET field1='value1', field2='value2' WHERE field3='value3' AND field4='value4'

vba access query with variables

I get the runtime error 3141 which says the SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect. On user form click, I'm trying to use a loop where multiple fields within a query are defined using variable inputs. Where am I going wrong here?
Private Sub Calculate_Click()
Dim db As Database
Dim x As Integer
Dim y As Integer
Dim WPmonthly As String ' field name for monthly written premium
Dim UPRmonthly As String ' field name for monthly unearned premium
Dim EPmonthly As String ' field name for monthly earned premium
Dim runningDate As Date
Dim useDateLower As Date
Dim useDateUpper As Date
Dim qry As dao.QueryDef
Months = Me.YearsBack * 12 + Month(Me.ValDate)
If Me.Period = "monthly" Then
Set db = CurrentDb
Set qry = CurrentDb.CreateQueryDef("MyQuery")
Debug.Print qry.SQL ' shows the SQL from MyQuery
For x = 1 To Months
runningDate = Format(DateAdd("m", -x + 1, Me.ValDate), "mm yyyy")
useDateLower = runningDate
useDateUpper = Format(DateAdd("m", -x + 2, Me.ValDate), "mm yyyy")
WPmonthly = "WP M" & Month(runningDate) & " " & Year(runningDate)
EPmonthly = "EP M" & Month(runningDate) & " " & Year(runningDate)
UPRmonthly = "UPR M" & Month(runningDate) & " " & Year(runningDate)
qry.SQL = "SELECT IIf([tblEPdata]![IssueDate]>" & useDateLower & ",IIf([tblEPdata]![IssueDate]<" & useDateUpper & ",[tblEPdata]![GrossPremium])) AS " & WPmonthly & " FROM tblEPdata;"
Next
qry.Close
End If
end sub
by seing your query i think that is the format for Dates should be between '' and yyyymmdd or yyyy-mm-dd format and for the last ; in the query statement.
You have something like:
useDateLower = 01/05/2016
Excel understand it but SQL does not, so, you must inclose your dates with '' or ## and your query ends like:
... [tblEPdata]![IssueDate]> '' " & useDateLower & " '' ,IIf([tb...
and you can add an Alias to your table.
qry.SQL = "SELECT IIf([TBL].[IssueDate]> ''" & useDateLower & _
"'',IIf([TBL].[IssueDate]< ''" & useDateUpper & _
"'',[TBL].[GrossPremium])) AS " & WPmonthly & _
" FROM tblEPdata AS [TBL]"
The first thing I would change is this line:
qry.SQL = _
"SELECT IIf([IssueDate] > #" & useDateLower & "#," & _
"IIf([IssueDate] < #" & useDateUpper & "#," & _
"[GrossPremium])) AS [" & WPmonthly & "] FROM tblEPdata;"
Also need brackets around WPmonthly. I would also try changing using bangs instead of periods (Me!Period).