ODBC connection using VBA - sql

I am getting an error message when I run my VBA code. I tried debugging and seems like there is something wrong with my connection string. I am getting an error message "Data source name not found and no default driver specified.
Sub Macro176()
Sheets("176Tk").Select
Dim i As Integer
i = 17
Set oConn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
oConn.Open "Driver={MySQL ODBC 5.1 Driver};" & _
"server=myserveraddress;" & _
"database=mydatabasename; uid= myuserId; pwd=mypassword;" & _
"option=3"
SQLstr = "SELECT SUBSTRING(dbo.collection_points.name, CHARINDEX('-', dbo.collection_points.name) + 2, 3) + 'Tk' AS 'Tank', " & _
"dbo.data_values.actual_date_time AS 'Date', " & _
"dbo.data_values.value_text AS 'Drain Time', " & _
"dbo.data_points.name AS 'Description', " & _
"dbo.data_values.user_id AS 'Field Operator' " & _
"FROM " & _
"dbo.collection_points INNER JOIN " & _
"dbo.area ON dbo.collection_points.area_rec_id = dbo.area.area_rec_id INNER JOIN " & _
"dbo.data_points ON dbo.collection_points.cp_rec_id = dbo.data_points.cp_rec_id INNER JOIN " & _
"dbo.data_values ON dbo.data_points.dp_rec_id = dbo.data_values.dp_rec_id INNER JOIN " & _
"dbo.system_levels ON dbo.area.ownership_sysid = dbo.system_levels.system_id " & _
"WHERE " & _
"((dbo.system_levels.description = 'CX5 Crude Tank Farm' and dbo.area.name = 'Crd TF Draining') OR " & _
"(dbo.system_levels.description = 'CX5 Melvindale Tank Farm' and dbo.area.name = 'Mel Tank Draining') OR " & _
"(dbo.system_levels.description = 'CX5 Tank Farm (CP)' and dbo.area.name = 'CP Tank Draining') OR " & _
"(dbo.system_levels.description = 'CX5 Unifiner Tank Farm' and dbo.area.name = 'LabT.F. Draining')) AND " & _
"((dbo.data_values.value_text <> 'Yes') AND (dbo.data_values.value_text <> 'Complete') AND (dbo.data_values.value_text <> 'Incomplete') AND " & _
"(dbo.collection_points.name NOT like '%Roof%')) AND " & _
"dbo.data_values.nominal_date_time>='2017-01-01 00:00:00' and " & _
"dbo.data_values.nominal_date_time<'2018-12-31 11:59:59' " & _
"ORDER BY dbo.collection_points.name, dbo.data_values.actual_date_time"
rs.Open SQLstr, oConn, adLockOptimistic, adCmdTable
Do Until rs.EOF
Sheets("176Tk").Cells(i, 1).Value = rs.Fields("Tank")
Sheets("176Tk").Cells(i, 2).Value = rs.Fields("Date")
Sheets("176Tk").Cells(i, 3).Value = rs.Fields("Drain Time")
Sheets("176Tk").Cells(i, 4).Value = rs.Fields("Field Operator")
i = i + 1
Loop
rs.Close
oConn.Close
Set rs = Nothing
Set oConn = Nothing
End Sub

Related

Dynamically run strings in a loop

I want to run a string dynamically.
I'm trying to run a VBA loop to build a SQL Union for each record after the first. There could be anywhere from 1 record to 100. I want this to be dynamic so I don't have to limit the number of entries.
Example:
If I have 5 records it creates the SQL query with 4 unions. All the same data etc.
I'm trying to do is this:
When someone opens a form they will enter a list of pack numbers, from that they will select the range of offers under each pack number (All Offers, Promo, or Buyer).
The code then builds a union query for each pack number based on the the offer range they selected.
The output is all the data on those Offers under that pack number.
My full code: (I thought it necessary to get the full picture)
Private Sub ReviewButton_Click()
Dim Owner As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdfPassThrough As QueryDef
Dim strSeasonSQL As String
Dim strSeason As String
Dim strType As String
Owner = GetNamespace("MAPI").Session.CurrentUser.AddressEntry
If Me.NewRecord = True Then
Me!Owner.Value = Owner
End If
Set db = CurrentDb
Set rs = CurrentDb.OpenRecordset("RetailEntry")
'Set rs = CurrentDb.OpenRecordset("SELECT * FROM RetailEntry")
strSeason = [Forms]![Retail_Navigation]![NavigationSubform].[Form]![cboSeason]
strType = rs.Fields("Offer").Value '[Forms]![ReviewButton]![RetailEntry].[Form]![Offer].Value
On Error GoTo 1
1:
'Build Initial Query based on first record and make sure there are records
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'All Offers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Offer") = "All Offers" Then
StrSQL = "Set NoCount ON DROP TABLE #catcov; " _
& "SELECT DISTINCT mailyear, offer, description, firstreleasemailed, season_id, offer_type, " _
& "case when description like '%Promo%' then 'Promo' " _
& "Else 'Buyer' end As addtype " _
& "INTO #catcov " _
strSELECT = "FROM supplychain_misc.dbo.catcov; " _
& "SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROM = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHERE = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL = StrSQL & vbCrLf & strSELECT & vbCrLf & strFROM & vbCrLf & strWHERE
'Promo/Core
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ElseIf rs.Fields("Offer") = "Promo" Or rs.Fields("Offer") = "Buyer" Then
StrSQL = "Set NoCount ON DROP TABLE #catcov; " _
& "SELECT DISTINCT mailyear, offer, description, firstreleasemailed, season_id, offer_type, " _
& "case when description like '%Promo%' then 'Promo' " _
& "Else 'Buyer' end As addtype " _
& "INTO #catcov " _
strSELECT = "FROM supplychain_misc.dbo.catcov; " _
& "SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROM = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHERE = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' and b.addtype = '" & strType & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL = StrSQL & vbCrLf & strSELECT & vbCrLf & strFROM & vbCrLf & strWHERE
End If
'Build/Loop Unions for each record after the first
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
rs.MoveNext
strType = rs.Fields("Offer").Value
Do Until rs.EOF = True
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'All Offers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If rs.Fields("Offer") = "All Offers" Then
StrUnion = "UNION SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROMnxt = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHEREnxt = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL2 = StrUnion & vbCrLf & strFROMnxt & vbCrLf & strWHEREnxt
'Promo/Buyer
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
ElseIf rs.Fields("Offer") = "Promo" Or rs.Fields("Offer") = "Buyer" Then
StrUnion = "UNION SELECT DISTINCT " _
& "a.PackNum " _
& ",a.Description " _
& ",a.CatID " _
& ",DATEPART(QUARTER, FirstReleaseMailed) as Quarter " _
& ",a.RetOne " _
& ",a.Ret2 " _
& ",a.ORIGINALRETAIL " _
& ",a.DiscountReasonCode " _
& ",b.Season_id " _
& ",a.year " _
& ",addtype "
strFROMnxt = "FROM PIC704Current a JOIN #CatCov b ON (a.CatID = b.Offer) and (a.Year = b.MailYear) " _
strWHEREnxt = "WHERE b.Offer_Type In('catalog', 'insert', 'kicker', 'statement insert', 'bangtail', 'onsert', 'outside ad') " _
& " and b.Season_id = '" & strSeason & "' and b.addtype = '" & strType & "' " _
& " and (Case when b.FirstReleaseMailed >= cast(dateadd(day, +21, getdate()) as date) then 1 else 0 end) = 1 "
StrSQL2 = StrUnion & vbCrLf & strFROMnxt & vbCrLf & strWHEREnxt
End If
'Move to next Record and loop till EOF
rs.MoveNext
Loop
'If there are no Records then error
Else
MsgBox "There are no Pack Numbers Entered."
End If
'END QUERY
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Build Retail Bump File Pass Through Query
db.QueryDefs.Delete "qryMaster"
Set qdfPassThrough = db.CreateQueryDef("qryMaster")
qdfPassThrough.Connect = "ODBC;DSN=SupplyChainMisc;Description=SupplyChainMisc;Trusted_Connection=Yes;DATABASE=SupplyChain_Misc;"
qdfPassThrough.ReturnsRecords = True
qdfPassThrough.sql = StrSQL & vbCrLf & StrSQL2
rs.Close
Set rs = Nothing
DoCmd.OpenForm "SubCanButton"
DoCmd.OpenQuery "MasterQuery"
DoCmd.Close acForm, "ReviewButton"
End Sub
First, you do a "union distinct" when you don't include ALL:
UNION ALL
SELECT DISTINCT ...
Thus, as your selected records seem the same, only one will returned.
Second, including ALL or not, your concept doesn't make much sense. Why union a lot of identical records? Even if they hold different IDs only, they seem to be pulled from the same table, which you could with a single query.
Third, casting a date value to a date value does nothing good, so:
cast(dateadd(day, +21, getdate()) as date)
can be reduced to:
dateadd(day, +21, getdate())

operation not allowed when object is closed "SQL connection giving error with VBA"

I am facing an issue while running a long SQL query with VBA, but when I run a simple one-line select query it works fine BUT
when I run the below complex query it fails, also I'd like to input some values from a defined range/cell into sql query like I would like to input L1100 as timezone from cell A2, what format should i use, any suggestions on this would be much appreciated
Public DBConn As ADODB.Connection
Public Sub createconn()
Dim UserId, Password As String
Set DBConn = New ADODB.Connection
Server = "XXXX"
UserId = "XXXXX"
Password = "XXXX"
With DBConn
.CommandTimeout = 30
.Open "PROVIDER=MSDASQL;" & _
"DRIVER={Microsoft ODBC for Oracle};" & _
"SERVER=" & Server & ";" & _
"UID=" & UserId & ";PWD=" & Password & ";"
End With
End Sub
Sub Stalecheck()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim DBresults As ADODB.Recordset
Dim sqlquery As String, wsData As Worksheet, Datasht As Worksheet
Dim elr As Long
Dim lRow As Long
Set DBresults = New ADODB.Recordset
Set wsData = Worksheets("Sheet1")
Set Datasht = ThisWorkbook.Sheets("Data")
'wsData.Range("U5:Y5", Range("U5").End(xlDown)).Clear
Datasht.Cells.ClearContents
'lRow = wsData.Cells(Rows.Count, 14).End(xlUp).Row
'Worksheets("UPDATER").Range("N2", "N" & lRow).Copy Destination:=Worksheets("UPDATER").Range("V5")
'Mainsheet.Range("B7:B15").ClearContents
If wsData.Range("B3").Value <> "" Then
Call createconn
'sqlquery = "select * from instrument_equity"
sqlquery = "select i.name, i.pkey, nvl(i.enddate,round((i.periodyears * 365.25),0) + vyc.asof) maturity," & vbNewLine & _
"nvl(i.period,i.enddate) period, vyc.asof, vyc.timezone, vyc.snaptime, vyc.rowkey, nvl(nvl(pfx.price, p.rate*100),vp.rate) rate," & vbNewLine & _
"nvl(nvl(pfx.updatetime, p.snaptime),vp.updatetime) updatetime, vms.symbol source" & vbNewLine & _
"from val_yield_curves vyc" & vbNewLine & _
"JOIN val_yc_def_elements el ON el.pkey=valuations_yieldcurves.getCurveDefinitionKey(vyc.asof, vyc.object_id)" & vbNewLine & _
"JOIN instruments i on i.pkey = el.instrument" & vbNewLine & _
"LEFT JOIN (SELECT asof, curve, instrument, rate*100 rate, quality, source, updatetime, bid, ask FROM val_prices_interestrates" & vbNewLine & _
"UNION SELECT asof, curve, instrument, rate*100, quality, source, updatetime, bid, ask FROM val_prices_basisswaps" & vbNewLine & _
"UNION SELECT asof, curve, instrument, rate*100, quality, source, updatetime, bid, ask FROM val_prices_oisrates" & vbNewLine & _
"UNION SELECT asof, curve, instrument, rate, quality, source, updatetime, bid, ask FROM val_prices_fx)" & vbNewLine & _
"vp ON i.pkey = vp.instrument" & vbNewLine & _
"and vp.asof=vyc.asof" & vbNewLine & _
"and vp.curve=vyc.rowkey" & vbNewLine & _
"LEFT JOIN prices_fixings p ON p.instrument = i.pkey and p.asof = vyc.asof" & vbNewLine & _
"LEFT JOIN val_prices_fxfixings pfx ON pfx.instrument = i.pkey" & vbNewLine & _
"and pfx.asof = vyc.asof" & vbNewLine & _
"and pfx.timezone = vyc.timezone" & vbNewLine & _
"LEFT JOIN val_mds_sources vms ON vms.pkey = vp.source" & vbNewLine & _
"WHERE vyc.asof = '11Jul20'" & vbNewLine & _
"and vyc.timezone = 'L1000'" & vbNewLine & _
"and vyc.object_id like 'CAD_IRIndex_3M'" & vbNewLine & _
"and i.type <> 'Future'" & vbNewLine & _
"ORDER BY vyc.object_id, i.type desc, el.type, i.ccy, i.ccy2, nvl(i.periodyears, nvl((i.enddate-trunc(sysdate))/365,0)), vyc.snaptime DESC"
'sqlquery = Left(sqlquery, Len(sqlquery) - 1) & ")"
DBresults.Open sqlquery, DBConn, adOpenDynamic
If Not DBresults.EOF Then Datasht.Range("A1").CopyFromRecordset DBresults
End If
Set DBresults = Nothing
Call close_conn
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Sub close_conn()
DBConn.Close
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

Error executing a dynamic query with inner join (VBA) to dynamic tables

I'm sorry for my English ;)
I have consulted a lot on the internet but I cannot find the solution
I must create a dynamic query, with a function.
This code works for me if the tables are not linked, but are in the same bbdd ACCESS 2016.
But I need them to be in another bbdd.
Can you help me?
It returns me that data is missing.
The query is made in access and modified in vba, adding the variables.
Ano and Trimestre are numerical, the others are text.
Public Function PRUEBA_INNER(ByVal TRIMESTRE As String,ByVal ANO As String) As Boolean
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim StrSQL As String
Set db = CurrentDb
StrSQL = "SELECT " & _
"PERSONAS.NOMBRE, " & _
"PERSONAS.MAIL, " & _
"PERSONAS.[NUMR_COLEG], " & _
"DATOS_" & ANO & ".ANO, " & _
"DATOS_" & ANO & ".TRIMESTRE " & _
"FROM " & _
"PERSONAS " & _
"INNER JOIN DATOS_" & ANO & " " & _
"ON PERSONAS.[NUMR_COLEG] = DATOS_" & ANO & ".NUMR_COLEG " & _
"GROUP BY " & _
"PERSONAS.NOMBRE, " & _
"PERSONAS.MAIL, " & _
"PERSONAS.[NUMR_COLEG], " & _
"DATOS_" & ANO & ".ANO, " & _
"DATOS_" & ANO & ".TRIMESTRE " & _
"HAVING (((DATOS_" & ANO & ".ANO)=" & ANO & ")" & _
" AND ((DATOS_" & ANO & ".TRIMESTRE)=" & TRIMESTRE & "))"
Set rs = db.OpenRecordset(StrSQL)
Do Until rs.EOF
debug.print rs!nombre
rs.MoveNext
Loop
rs.Close: Set rs = Nothing
db.Close: Set db = Nothing
End Function
Debug.print:
SELECT
PERSONAS.NOMBRE,
PERSONAS.MAIL,
PERSONAS.[NUMR_COLEG],
DATOS_2018.ANO,
DATOS_2018.TRIMESTRE
FROM
PERSONAS
INNER JOIN
DATOS_2018
ON
PERSONAS.[NUMR_COLEG] = DATOS_2018.NUMR_COLEG
GROUP BY
PERSONAS.NOMBRE,
PERSONAS.MAIL,
PERSONAS.[NUMR_COLEG],
DATOS_2018.ANO,
DATOS_2018.TRIMESTRE
HAVING (((DATOS_2018.ANO)=2018) AND ((DATOS_2018.TRIMESTRE)=2))
Error message:
nÂș 3061
Few parameters.
1 expected

Quotations in Access String from Excel VBA

Ok I am having a Problem using VBA from Excel 2010 to Query data in access, the problem comes when the variable Descripcheck, or Grouplocal, some of the descriptions have a "" in the excel cell so when it pulls the string itself this causes the query function gets a syntax error. Any ideas?
PMnum = Cells(B, 3)
Grouplocal = Cells(B, 4)
Descripcheck = Cells(B, 6)
DevTyp = Cells(B, 5)
TagName = Cells(B, 2)
If PMnum = "" Then
PMnum = " IS NULL"
Else:
PMnum = "=" & PMnum
End If
If Grouplocal = "" Then
Grouplocal = " IS NULL"
Else:
Grouplocal = "=" & Chr$(34) & Grouplocal & Chr$(34)
End If
If Descripcheck = "" Then
Descripcheck = " IS NULL"
Else:
Descripcheck = "=" & Chr$(34) & Descripcheck & Chr$(34)
End If
If DevTyp = "" Then
DevTyp = " IS NULL"
Else:
DevTyp = "=" & Chr$(34) & DevTyp & Chr$(34)
End If
If TagName = "" Then
TagName = " IS NULL"
Else:
TagName = "=" & Chr$(34) & TagName & Chr$(34)
End If
sCmndString = "SELECT Site_Data.Pass_Fail, Site_Data.Tag_Name, Site_Data.[PM_#],Site_Data.Group_Location_Reference, Site_Data.Device_Type, Site_Data.Description, Site_Data.Set_Point, Site_Data.Set_Point_Units, Site_Data.Fail_Low, Site_Data.Fail_High, Site_Data.As_Found, Site_Data.As_Left, Site_Data.Manufacturer_SN, Site_Data.Year_Put_Into_Service, Site_Data.Date_of_Test, Site_Data.Time_To_Complete, Site_Data.Service, Site_Data.Comments, Site_Data.Site, Site_Data.Year, Site_Data.Month " & _
"FROM Site_Data WHERE (((Site_Data.[PM_#])" & PMnum & ") AND " & _
"((Site_Data.Group_Location_Reference)" & Grouplocal & ") AND " & _
"((Site_Data.Device_Type)" & DevTyp & ") AND " & _
"((Site_Data.Description)" & Descripcheck & ") AND " & _
"((Site_Data.Site)=" & Chr$(34) & SiteName & Chr$(34) & ") AND " & _
"((Site_Data.Year)=" & Chr$(34) & yrs & Chr$(34) & ") AND " & _
"((Site_Data.Month)=" & Chr$(34) & Mnth & Chr$(34) & ") AND " & _
"((Site_Data.Tag_Name)" & TagName & "));"
Set rs = New ADODB.Recordset
rs.Open sCmndString, cnt, 2, 3, 1
If you keep fooling around with those "s and Chr$(34)s you'll drive yourself crazy. Try using a parameterized query instead. Consider the following (simplified) example. It uses some test data in Access...
Site_ID Device_Type Description
------- ----------- ------------
1 Type1 test1
2 Type1
3 Type1
4 Type2 "some" value
5 Type2 "some" value
6 Type2
7 Type2
8 Type2
...an Excel sheet that looks like this...
...and the code behind the button is
Option Explicit
Public Sub AccessLookup()
Dim con As ADODB.Connection, cmd As ADODB.Command, rst As ADODB.Recordset
Dim DevTyp As Variant, Descripcheck As Variant
Dim s As String, i As Long
s = Trim(CStr(Range("B1").Value))
DevTyp = IIf(Len(s) = 0, Null, s)
s = Trim(CStr(Range("B2").Value))
Descripcheck = IIf(Len(s) = 0, Null, s)
Set con = New ADODB.Connection
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;"
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandText = _
"SELECT COUNT(*) AS n FROM Site_Data " & _
"WHERE Device_Type " & IIf(IsNull(DevTyp), "IS NULL ", "= ? ") & _
"AND Description " & IIf(IsNull(Descripcheck), "IS NULL ", "= ? ")
i = 0
If Not IsNull(DevTyp) Then
cmd.CreateParameter "?", adVarWChar, adParamInput, 255
cmd.Parameters(i).Value = DevTyp
i = i + 1
End If
If Not IsNull(Descripcheck) Then
cmd.CreateParameter "?", adVarWChar, adParamInput, 255
cmd.Parameters(i).Value = Descripcheck
i = i + 1
End If
Set rst = cmd.Execute
Range("B6").Value = rst("n").Value
rst.Close
Set rst = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub