Update SQL in Access VBA -- Updating Table Values From Another Table - sql

I'm fairly new to Access VBA and SQL coding. So far, I've been able to find most of the answers to issues I've had by using the internet. I'm currently trying to write some code in MS Access (2013) VBA that updates the data in one table from another table in the same database when a particular form closes.
I've worked out several errors so far, but I'm stuck on a syntax error in the "UPDATE" for SQLReplace. There could be other errors that I don't know about yet, but I'm not sure. Any help/Guidance would be greatly appreciated!
Thanks!
Private Sub Form_Close()
Dim SQLMove As String
Dim SQLReplace As String
Dim CountyCaseType As String
Dim CaseNumber As String
Dim County As String
Dim FirstName As String
Dim MiddleName As String
Dim LastName As String
Dim Facility As String
Dim VOL As String
Dim Diagnosis As String
Dim AppearanceWaived As String
Dim Dismissed As String
Dim HearingResults As String
Dim Disposition As String
Dim DOB As String
Dim Minor As String
Dim Sex As String
Dim ClerkName As String
Dim Judge As String
Dim CourtDate As String
CountyCaseType = "Tables!tblTemp.CountyCaseType.Value"
CaseNumber = "Tables!tblTemp.CaseNumber.Value"
County = "Tables!tblTemp.County.Value"
FirstName = "Tables!tblTemp.FirstName.Value"
MiddleName = "Tables!tblTemp.MiddleName.Value"
LastName = "Tables!tblTemp.LastName.Value"
Facility = "Tables!tblTemp.Facility.Value"
VOL = "Tables!tblTemp.VOL.Value"
Diagnosis = "Tables!tblTemp.Diagnosis.Value"
AppearanceWaived = "Tables!tblTemp.AppearanceWaived.Value"
Dismissed = "Tables!tblTemp.Dismissed.Value"
HearingResults = "Tables!tblTemp.HearingResults.Value"
Disposition = "Tables!tblTemp.Disposition.Value"
DOB = "Tables!tblTemp.DOB.Value"
Minor = "Tables!tblTemp.Minor.Value"
Sex = "Tables!tblTemp.Sex.Value"
ClerkName = "Tables!tblTemp.Clerk.Value"
Judge = "Tables!tblTemp.Judge.Value"
CourtDate = "Tables!tblTemp.CourtDate.Value"
SQLMove = "INSERT INTO tblCalendar SELECT * FROM tblTemp"
SQLReplace = "UPDATE tblCalendar " & _
"SET tblCalendar.CountyCaseType.Value = CountyCaseType, " & _
" tblCalendar.CaseNumber.Value = CaseNumber, " & _
" tblCalendar.County.Value = County, " & _
" tblCalendar.FirstName.Value = FirstName, " & _
" tblCalendar.MiddleName.Value = MiddleName, " & _
" tblCalendar.LastName.Value = LastName, " & _
" tblCalendar.Facility.Value = Facility, " & _
" tblCalendar.VOL.Value = VOL, " & _
" tblCalendar.Diagnosis.Value = Diagnosis, " & _
" tblCalendar.AppearanceWaived.Value = AppearanceWaived, " & _
" tblCalendar.Dismissed.Value = Dismissed, " & _
" tblCalendar.HearingResults.Value = HearingResults, " & _
" tblCalendar.Disposition.Value = Disposition, " & _
" tblCalendar.DOB.Value = DOB, " & _
" tblCalendar.Minor.Value = Minor, " & _
" tblCalendar.Sex.Value = Sex, " & _
" tblCalendar.ClerkName.Value = Clerk, " & _
" tblCalendar.Judge.Value = Judge, " & _
"FROM tblTemp " & _
"Where 'CourtDate = tblCalendar.CourtDate.Value'"
DoCmd.SetWarnings False
DoCmd.RunSQL (SQLMove)
DoCmd.RunSQL (SQLReplace)
DoCmd.SetWarnings True
End Sub

There are several potential errors in your code:
You do not need to add .Value to the end of an attribute to get its actual value.
As you are working directly in Access, you to not need the Tables! part either. That is the syntax used when dealing with recordsets. For example, write tblTemp.CountyCaseType instead of Tables!tblTemp.CountyCaseType.Value
The values of your variables are not in the SQL string. You have to concatenate them to the SQLReplace String using [&]. For example, write
SQLReplace = "UPDATE tblCalendar " & _
"SET tblCalendar.CountyCaseType = " & CountyCaseType & ", " & _
" tblCalendar.CaseNumber = " & CaseNumber & ", " & _
....
As #AlanHadsell pointed out, remove the single quotes from the WHERE clause.
Where 'CourtDate = tblCalendar.CourtDate.Value'
should be
WHERE CourtDate = tblCalendar.CourtDate
But as I said in 3) CourTDate is a String variable, so it needs to be concatenated. Your final WHERE clause should be:
"WHERE " & CourtDate & " = tblCalendar.CourtDate"
You don't need the FROM tblTemp clause in the SQLReplace String.
EDIT: As #Parfait pointed out, tblTemp does not exist in scope of the SQLReplace statement. You should do an INNER JOIN to fix that:
UPDATE tblCalendar INNER JOIN tblTemp ON tblCalendar.CourtDate = tblTemp.CourtDate SET ...
After fixing everything, your final code should look like:
Private Sub Form_Close()
Dim SQLMove As String
Dim SQLReplace As String
Dim CountyCaseType As String
Dim CaseNumber As String
Dim County As String
Dim FirstName As String
Dim MiddleName As String
Dim LastName As String
Dim Facility As String
Dim VOL As String
Dim Diagnosis As String
Dim AppearanceWaived As String
Dim Dismissed As String
Dim HearingResults As String
Dim Disposition As String
Dim DOB As String
Dim Minor As String
Dim Sex As String
Dim ClerkName As String
Dim Judge As String
Dim CourtDate As String
CountyCaseType = "tblTemp.CountyCaseType"
CaseNumber = "tblTemp.CaseNumber"
County = "tblTemp.County"
FirstName = "tblTemp.FirstName"
MiddleName = "tblTemp.MiddleName"
LastName = "tblTemp.LastName"
Facility = "tblTemp.Facility"
VOL = "tblTemp.VOL"
Diagnosis = "tblTemp.Diagnosis"
AppearanceWaived = "tblTemp.AppearanceWaived"
Dismissed = "tblTemp.Dismissed"
HearingResults = "tblTemp.HearingResults"
Disposition = "tblTemp.Disposition"
DOB = "tblTemp.DOB"
Minor = "tblTemp.Minor"
Sex = "tblTemp.Sex"
ClerkName = "tblTemp.Clerk"
Judge = "tblTemp.Judge"
CourtDate = "tblTemp.CourtDate"
SQLMove = "INSERT INTO tblCalendar SELECT * FROM tblTemp"
SQLReplace = "UPDATE tblCalendar " & _
"INNER JOIN tblTemp ON tblCalendar.CourtDate = tblTemp.CourtDate " & _
"SET tblCalendar.CountyCaseType = " & CountyCaseType & ", " & _
" tblCalendar.CaseNumber = " & CaseNumber & ", " & _
" tblCalendar.County = " & County & ", " & _
" tblCalendar.FirstName = " & FirstName & ", " & _
" tblCalendar.MiddleName = " & MiddleName & ", " & _
" tblCalendar.LastName = " & LastName & ", " & _
" tblCalendar.Facility = " & Facility & ", " & _
" tblCalendar.VOL = " & VOL & ", " & _
" tblCalendar.Diagnosis = " & Diagnosis & ", " & _
" tblCalendar.AppearanceWaived = " & AppearanceWaived & ", " & _
" tblCalendar.Dismissed = " & Dismissed & ", " & _
" tblCalendar.HearingResults = " & HearingResults & ", " & _
" tblCalendar.Disposition = " & Disposition & ", " & _
" tblCalendar.DOB = " & DOB & ", " & _
" tblCalendar.Minor = " & Minor & ", " & _
" tblCalendar.Sex = " & Sex & ", " & _
" tblCalendar.ClerkName = " & Clerk & ", " & _
" tblCalendar.Judge = " & Judge
DoCmd.SetWarnings False
DoCmd.RunSQL (SQLMove)
DoCmd.RunSQL (SQLReplace)
DoCmd.SetWarnings True
End Sub
To finish, instead of declaring a String variable for each attributes in tableTemp that you want to copy, and then assigning some values to them, you can simply omit the declarations and put the attributes dicrectly in the SQL. That will geatly reduce the length of your code as follow:
Private Sub Form_Close()
Dim SQLMove As String
Dim SQLReplace As String
SQLMove = "INSERT INTO tblCalendar SELECT * FROM tblTemp"
SQLReplace = "UPDATE tblCalendar " & _
"INNER JOIN tblTemp ON tblCalendar.CourtDate = tblTemp.CourtDate " & _
"SET tblCalendar.CountyCaseType = tblTemp.CountyCaseType, " & _
" tblCalendar.CaseNumber = tblTemp.CaseNumber, " & _
" tblCalendar.County = tblTemp.County, " & _
" tblCalendar.FirstName = tblTemp.FirstName, " & _
" tblCalendar.MiddleName = tblTemp.MiddleName, " & _
" tblCalendar.LastName = tblTemp.LastName, " & _
" tblCalendar.Facility = tblTemp.Facility, " & _
" tblCalendar.VOL = tblTemp.VOL, " & _
" tblCalendar.Diagnosis = tblTemp.Diagnosis, " & _
" tblCalendar.AppearanceWaived = tblTemp.AppearanceWaived, " & _
" tblCalendar.Dismissed = tblTemp.Dismissed, " & _
" tblCalendar.HearingResults = tblTemp.HearingResults, " & _
" tblCalendar.Disposition = tblTemp.Disposition, " & _
" tblCalendar.DOB = tblTemp.DOB, " & _
" tblCalendar.Minor = tblTemp.Minor, " & _
" tblCalendar.Sex = tblTemp.Sex, " & _
" tblCalendar.ClerkName = tblTemp.ClerkName, " & _
" tblCalendar.Judge = tblTemp.Judge"
DoCmd.SetWarnings False
DoCmd.RunSQL (SQLMove)
DoCmd.RunSQL (SQLReplace)
DoCmd.SetWarnings True
End Sub

Remove the single quotes from "Where 'CourtDate = tblCalendar.CourtDate.Value'"

Related

find missing number buckets

I was wondering if there's a better way
I need to find missing number buckets. There's a set of number buckets in which the weights are distributed. I want to make sure that if the user misses a number somewhere, his attention is drawn to it and hes told that he's missing some buckets, otherwise his data for these will not show.
I already found each missing number but it shows a line for each and the user is only interested in the entire bucket.
so, I need the thing on the left to become the thing on the right. The FROM and TO is what I have to work with.
I have a feeling there's some beautiful VBA solution for this, something with arrays :)
Besides all this ugliness that I wrote, to get the original missing weight, I had to create a table with all weights from 0 to 1000. there has to be a better way
Sub sbMissingBuckets()
Dim vrQDF As Object
Dim vrSQL As String
Dim vrQueryName As String
Dim vrCountsMissingBuckets As Long
sbWOff
DoCmd.RunSQL "DELETE FROM MissingServicesShippingWeightBuckets"
Dim vrRs1 As DAO.Recordset
Dim vrServicesShippingWeightCollectionID As Long
Set vrRs1 = CurrentDb.OpenRecordset("SELECT ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID FROM ServicesShippingWeightBuckets GROUP BY ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID " & _
", ServicesShippingWeightBuckets.IsMultiweight HAVING (((ServicesShippingWeightBuckets.IsMultiweight)=False));")
Do Until vrRs1.EOF
vrServicesShippingWeightCollectionID = vrRs1("ServicesShippingWeightCollectionID")
vrSQL = "SELECT ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID, AllWeights.Weight FROM ServicesShippingWeightBuckets " & _
", AllWeights GROUP BY ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID, AllWeights.Weight, IIf([WeightFromInequalitySymbolID]=1,IIf([WeightToInequalitySymbolID]=3,[Weight]>[WeightFrom] " & _
"AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>[WeightFrom] AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>[WeightFrom] " & _
"AND [Weight]<=999999999)) & IIf([WeightFromInequalitySymbolID]=2,IIf([WeightToInequalitySymbolID]=3,[Weight]>=[WeightFrom] AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>=[WeightFrom] " & _
"AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>=[WeightFrom] AND [Weight]<=999999999)), ServicesShippingWeightBuckets.IsMultiweight " & _
"HAVING (((ServicesShippingWeightBuckets.ServicesShippingWeightCollectionID)=" & vrServicesShippingWeightCollectionID & ") AND ((IIf([WeightFromInequalitySymbolID]=1,IIf([WeightToInequalitySymbolID]=3,[Weight]>[WeightFrom] " & _
"AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>[WeightFrom] AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>[WeightFrom] " & _
"AND [Weight]<=999999999)) & IIf([WeightFromInequalitySymbolID]=2,IIf([WeightToInequalitySymbolID]=3,[Weight]>=[WeightFrom] AND [Weight]<[WeightTo]) & IIf([WeightToInequalitySymbolID]=4,[Weight]>=[WeightFrom] " & _
"AND [Weight]<=[WeightTo]) & IIf(IsNull([WeightToInequalitySymbolID]),[Weight]>=[WeightFrom] AND [Weight]<=999999999)))=-1) " & _
"AND ((ServicesShippingWeightBuckets.IsMultiweight)=False)) ORDER BY AllWeights.Weight;"
vrQueryName = "qMissingBucketsBase"
fnDeleteObjectIfExists "Query", vrQueryName
Set vrQDF = CurrentDb.CreateQueryDef(vrQueryName, vrSQL)
'count qMissingBuckets
vrCountsMissingBuckets = dCount("cTo", "qMissingBuckets")
'if 0 do nothing
If vrCountsMissingBuckets > 0 Then
'loop thoruhg and onl add records to the table if the diff is more than 1
DoCmd.OpenQuery "qMissingBuckets2"
DoCmd.OpenQuery "qMissingBuckets3"
Dim vrRs2 As DAO.Recordset
Dim vrFrom As Long
Dim vrTo As Long
Dim vrDiff As Long
Dim vrPlaceholder As Boolean
Dim vrFromPlaceholder As Variant
Set vrRs2 = CurrentDb.OpenRecordset("mtT")
Do Until vrRs2.EOF
vrFrom = vrRs2("cFrom")
vrTo = vrRs2("cTo")
vrDiff = vrRs2("cDiff")
If vrDiff > 1 Then
If vrPlaceholder = False Then
If vrDiff < 99999 Then
DoCmd.RunSQL "INSERT INTO MissingServicesShippingWeightBuckets (ServicesShippingWeightCollectionID, ServicesShippingWeightBucket, WeightFromInequalitySymbolID, WeightFrom, WeightToInequalitySymbolID, WeightTo) SELECT " & vrServicesShippingWeightCollectionID & _
", '>=" & vrFrom & " and <" & vrTo & "', 2 as WeightFromInequalitySymbolID, " & vrFrom & " as WeightFrom, 3 as WeightToInequalitySymbolID, " & vrTo & " as WeightTo"
End If
Else
DoCmd.RunSQL "INSERT INTO MissingServicesShippingWeightBuckets (ServicesShippingWeightCollectionID, ServicesShippingWeightBucket, WeightFromInequalitySymbolID, WeightFrom, WeightToInequalitySymbolID, WeightTo) SELECT " & vrServicesShippingWeightCollectionID & _
", '>=" & vrFromPlaceholder & " and <" & vrTo & "', 2 as WeightFromInequalitySymbolID, " & vrFromPlaceholder & " as WeightFrom, 3 as WeightToInequalitySymbolID, " & vrTo & " as WeightTo"
vrPlaceholder = False
vrFromPlaceholder = Null
End If
ElseIf vrDiff = 1 Then
If vrPlaceholder = False Then
vrFromPlaceholder = vrFrom
vrPlaceholder = True
End If
End If
vrRs2.MoveNext
Loop
vrRs2.Close
Set vrRs2 = Nothing
End If
vrRs1.MoveNext
Loop
vrRs1.Close
Set vrRs1 = Nothing
sbWOn
End Sub

Trying to upsize from Access tables to SQL Server linked tables. Code works fine with Access but gives a "ODBC call failed 3146" when connected to SQL

Public Sub UpdateTermFeedbackAddlReqt(ByVal runid As Integer, ByVal BHTerm As String, ByVal username As String, ByVal currtime As Double)
Dim db As DAO.Database
Dim rs As DAO.Recordset
DoCmd.SetWarnings False
Set db = CurrentDb
sql = "SELECT tbl_SCG_ExpectedTraffic.BHTerm, Sum(tbl_SCG_ExpectedTraffic.CurrSent2) AS SumOfCurrSent2, iif(Sum([CurrSent2]) = 0, 0, Sum([Accepted])/Sum([CurrSent2])) AS [Term Accept Rate], Sum(tbl_SCG_ExpectedTraffic.Accepted) AS SumOfAccepted, Sum(tbl_SCG_ExpectedTraffic.Rejected) AS SumOfRejected, Sum(tbl_SCG_ExpectedTraffic.Modified) AS SumOfModified, Sum(tbl_SCG_ExpectedTraffic.CurrCalledin) AS SumOfCalledin, Sum([ExpTotal])-Sum([CurrSent2]) AS [Need to Send]" & _
" FROM tbl_SCG_ExpectedTraffic" & _
" GROUP BY Date(), tbl_SCG_ExpectedTraffic.BHTerm, tbl_SCG_ExpectedTraffic.OptRunID" & _
" HAVING (((tbl_SCG_ExpectedTraffic.OptRunID)=" & runid & ") And BHTerm= """ & BHTerm & """);"
Set rs = db.OpenRecordset(sql, dbOpenDynaset, dbSeeChanges)
DoCmd.RunSQL ("Update tbl_SCG_TerminalFeedback set [CurrentSend2] = " & rs![SumOfCurrSent2] & ", [Term Accept Rate] =" & rs![Term Accept Rate] & ", Accepted= " & rs![SumOfAccepted] & ", Rejected = " & rs![SumOfRejected] & ", Modified =" & rs![SumOfModified] & ", Calledin = " & rs![SumOfCalledin] & ", AddlReqst =" & rs![Need To Send] & _
",[Last Update User] =""" & username & """, [Last Update Time]= " & currtime & " , HrDiff = iif( isnull(DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID = " & runid & """)), 0, Round((" & currtime & " - DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID =" & runid & """)) * 24, 1))" & _
" where OptRunID = " & runid & " And Term = """ & BHTerm & """")
DoCmd.SetWarnings True
rs.Close
db.Close
End Sub

Combobox filtering for listbox output is not working as expected

I have a few controls (Combobox's I call DDL's) that I use as filters for a dynamic query, shown below.
I have a region, division filter - and BCI/BCV/ABC/etc dropdowns.
When I select the region and division, the output list box correctly filters out everything except THOSE region/divisions. Good.
The problem comes in when I use the other DDL's, ABD/BCI/etc... those do not filter out correctly and I think it is with my and/or clauses below.
Can anyone see anything glaring or point me in the right direction to get this so that every control and ddl element filters out the data it is intended for - while keeping it in a format where the SQL itself is part of a string, like in my example?
Private Sub goBtn_Click()
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs " & _
"WHERE DivisionDDL = [Division_Name] and RegionDDL = [Region_Name] " & _
" and ( [BCI_Ind] = CheckBCI.value or [BCV_Ind] = CheckBCV.value or [ABC_Ind] = CheckABC.value " & _
" or BCIServiceDDL = [Tier]" & _
" or BCVServiceDDL = [Description_2]" & _
" or ABCServiceDDL = [Unit_ID] )" & _
"ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
One of the combo box DDL control codes. There are check boxes that make the combo box visible or not visible.
Private Sub CheckBCV_Click()
If Me.CheckBCV = vbTrue Then
Me.BCVServiceDDL.Visible = True
Me.BCVServiceDDL = "Select:"
strSQL = "SELECT Distinct subs.[Description_2] FROM dbo_ndw_bc_subs "
Me.BCVServiceDDL.RowSource = strSQL
Me.BCVServiceDDL.Requery
Else
Me.BCVServiceDDL.Visible = False
Me.BCVServiceDDL = ""
End If
End Sub
Edit: Added additional code to the first code block for context, and updated some comments.
To reiterate the point of my question - Since some of the DDL's work as expected while the others do not. Is it in the AND/OR section where I have a problem - or am I forced to do an IF/IIF statement in the select. (And if I do this IF solution - how would that be incorporated into a string the way I have it now, I have not seen an example of this in my research on a resolution).
I think your top code sample should read more like this:
Private Sub goBtn_Click()
Dim strSQL As String
Dim strWhere As String
Dim strOp As String
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs "
strWhere = ""
strOp = ""
If Not IsNull(Me.DivisionDDL.Value) Then
strWhere = strWhere & strOp & "(Division_Name = """ & Me.DivisionDDL.Value & """)"
strOp = " And "
End If
If Not IsNull(Me.RegionDDL.Value) Then
strWhere = strWhere & strOp & "(Region_Name = """ & Me.RegionDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCI.Value Then
strWhere = strWhere & strOp & "(Tier = """ & Me.BCIServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCV.Value Then
strWhere = strWhere & strOp & "(Description_2 = """ & Me.BCVServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckABC.Value Then
strWhere = strWhere & strOp & "(Unit_ID = """ & Me.ABCServiceDDL.Value & """)"
strOp = " And "
End If
If Len(strWhere) > 0 then
strSQL = strSQL & " WHERE " & strWhere
End If
strSQL = strSQL & " ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
This is wordier, but much closer to correct. P.S. I guessed that all values are strings. If not remove the quoting around non-string values.

VBA - Get all value in Array as subsequent strings

I have connected VBA & SQL Database in order to pull information.
I have written a script that returns exactly what I want but I would like to make it dynamical (Change years used etc.) and I am here running into problems.
I need to have a special line in my SQL Query which only has 1 thing that changes between the lines (Number of lines need to change and the Case when y.Date_Year = )
I get an Error message in the below code saying that there is a Type mismatch at the " & " sign right above my "period ()" array.
Sub test()
Dim SQLDB As ADODB.Connection
Dim sQuery As String
Dim info()
Dim Start_D As String
Dim End_D As String
Dim Numerator_Used As String
Dim Denominator_Used As String
Dim Number_Years As Integer
Dim period()
Numerator_Used = Range("Numerator")
Denominator_Used = Range("Denominator")
Start_D = Range("Start_Date")
End_D = Range("End_Date")
Range("A11:J100000").Cells.ClearContents
Number_Years = End_D - Start_D
ReDim period(Number_Years + 1)
For i = 0 To Number_Years
period(i + 1) = ",sum(case when y.date_year = " & Start_D + i & " then n." & Numerator_Used & " end) / sum(case when y.date_year = " & Start_D + i & " then s." & Denominator_Used & " end) as '" & Numerator_Used & "/" & Denominator_Used & " " & Start_D + i & "' & _ "
Next i
' Get Margin Expectation Changes
sQuery ="select m.date_month" & _
" m.date_month " & _
period() & _
" from " & Numerator_Used & " as n" & _
" inner join " & Denominator_Used & " as s on s.company_id = n.company_id" & _
" and s.date_month_id = n.date_month_id" & _
" and s.date_year_id = n.date_year_id" & _
" inner join date_year as y on y.date_year_id = n.date_year_id" & _
" inner join date_month as m on m.date_month_id = n.date_month_id" & _
" where y.date_year between " & Start_D & " and " & End_D & " " & _
" and n." & Numerator_Used & " <> 0" & _
" and s." & Denominator_Used & " <> 0" & _
" group by m.date_month;"
Set rs = Common.SQL_Read(SQLDB, sQuery)
ThisWorkbook.Worksheets("Sheet1").Range("A11").CopyFromRecordset rs
Set SQLDB = Common.SQL_Close(SQLDB)
End Sub
As i mentioned in the ocmment to the question, you can not explicity convert period() data into string as it is an array of variant data type (each undefined variable is treated as variant data type). You have to loop through the array data, i.e.:
For i = LBound(period()) To UBound(period())
sQuery = sQuery & period(i) & "...."
Next
'finally:
sQuery = "SELECT ... " & sQuery & " ...."
Change the code as i mentioned above and let me know if it works.

access 2013 increasing quantity in a table field

Good day. I'm a little stumped about what is happening in my code. I have a userform which collects txtQntyRecd and cboSupplySource. I calculate the lookupValue. And it works just fine. It successfully places the txtQntyRecd in the correct tblWarehouseLocations.WQuantity location. The code is:
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = '" & Me.txtQntyRecd & "'" & _
"WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError
What I want to do is add the next quantity to the same location. I get weird results if I change the SET statement to the following:
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + '" & Me.txtQntyRecd & "'"
If I put 200 in the first statement, I get 200 in my WQuantity field. When I change to the second statement and I try to add 1 to the 200 I get a result of 211. If I add 1 again, the result is 223. Add 1 again, the result is 236.
Could someone explain what is happening and why the results aren't 201, 202 and 203? In the future I will need to subtract quantities from WQuantity as well.
Thanks
You're adding quotes around an integer and appending it as a string. Change it to:
".....
SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & val(Me!txtQntyRecd) & "....
...."
I've changed the . to a ! as I think it's still a nice distinction between objects properties and controls, and used the val function as it converts the string number value to the integer value.
This is your query in full:
' When I use values from controls, I like to store them in vars
Dim quantityReceived As integer
quantityReceived = val(Me!txtQntyRecd)
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = tblWarehouseLocations.WQuantity + " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
I solved the problem. I created a SELECT query to get the present amount in WQuantity. Now quantityReceived = Me!txtQntyRecd + the present amount. With SET tblWarehouseLocations.WQuantity = " & quantityReceived it works fine. However, if just seems so cumbersome.
' lookupValue gives the index into the tblWarehouseLocations where WQuantity resides
Dim lookupValue As Integer
lookupValue = DLookup("[WLocation_ID]", "[tblWarehouseLocations]", "[Location_Name] = '" & Me.cboWLocation & "'")
'Define SQL Query
strSQL = "select tblWarehouseLocations.WQuantity FROM tblWarehouseLocations WHERE (((tblWarehouseLocations.WLocation_ID)= " & lookupValue & "))"
Set rs = db.OpenRecordset(strSQL)
If IsNull(rs!WQuantity) Then
dbvalue = 0
Else
dbvalue = rs!WQuantity
End If
Dim quantityReceived As Integer
quantityReceived = Val(Me!txtQntyRecd) + dbvalue
updateQnty = "UPDATE tblSupplySources INNER JOIN ((tblWarehouseLocations " & _
"INNER JOIN tblSupplySource_WarehouseLocation ON tblWarehouseLocations.WLocation_ID = tblSupplySource_WarehouseLocation.SWLocation_ID)) " & _
"ON tblSupplySources.SupplySourceID = tblSupplySource_WarehouseLocation.Supply_Source_ID " & _
"SET tblWarehouseLocations.WQuantity = " & quantityReceived & _
" WHERE (((tblSupplySource_WarehouseLocation.Supply_Source_ID)= " & Me.cboSupplySource & ") " & _
" AND ((tblWarehouseLocations.WLocation_ID)=" & lookupValue & "))"
CurrentDb.Execute updateQnty, dbFailOnError