Using ADODB within Access - vba

I'm trying to use adodb connection withing access vba, and it doesn't return me anydata, I guess my problem would be the connection, even though i'm using CurrentProject.Connection.
Need help please, here is my code
Dim cnThisConnect As New ADODB.Connection
Dim rsExpenses As New ADODB.Recordset
Dim sQuery As String
sQuery = "SELECT [ShippingSoldPrice] , ShippingPurchaseTaxe FROM Vehicles LEFT JOIN Contacts AS C ON
Vehicles.CustomerID = C.ID"
sQuery = sQuery & " Where " & Me.Filter
Set cnThisConnect = CurrentProject.Connection
rsExpenses.Open sQuery, cnThisConnect, adOpenDynamic, adLockOptimistic
If Not rsExpenses.EOF Then

Try to remove the line containing the where clause maybe this is the problem
'sQuery = sQuery & " Where " & Me.Filter
then check the returning records, if there are records then the problem is in the filter conditions.
Hope this may help

Related

VBA to query field contents in CSV

I'm struggling with ADO connections/recordsets.
My problem statement is: a function that will return the first value of a chosen field, in a chosen .csv file.
I am doing this to identify variably-named .csv files before adding the data to the relevant tables in a database. I am making the assumption that this field is always present and that either it is consistent throughout the file, or only relevant ones are grouped (this is controlled higher up the chain and is certain enough).
My code is being run as part of a module in an MS Access database:
Public Function GetFirstItem(File As Scripting.File, Field As String)
Dim Conn As ADODB.Connection, Recordset As ADODB.Recordset, SQL As String
Set Conn = New ADODB.Connection
Set Recordset = New ADODB.Recordset
'Microsoft.ACE.OLEDB.16.0 / Microsoft.Jet.OLEDB.4.0
Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=""" & File.ParentFolder & _
"""; Extended Properties=""text;HDR=Yes;FMT=Delimited;"";"
SQL = "SELECT " & Field & " FROM """ & File.Name & """ LIMIT 1"
Debug.Print Conn.ConnectionString
Debug.Print SQL
Conn.Open
Recordset.Source = SQL
Recordset.ActiveConnection = Conn.ConnectionString
Recordset.Open
Recordset.MoveFirst
'GetFirstItem = Recordset!Questionnaire
Recordset.Close
Conn.Close
Set Recordset = Nothing
Set Conn = Nothing
End Function
ConnectionString = Provider=Microsoft.ACE.OLEDB.16.0;Data Source="D:\Documents\Jobs\TestPath"; Extended Properties="text;HDR=Yes;FMT=Delimited;";
Field = Questionnaire
SQL = SELECT Questionnaire FROM "test.csv" LIMIT 1
I get an error on Recordset.Open of:
This may be (is probably) down to a complete lack of understanding of how ADO connections/recordsets work. I have tried sans-quotes and it complains about a malformed FROM expression. Additionally, once this hurdle is overcome I am unsure of the syntax of how to return the result of my query. If there is a better way of doing this I am all ears!
Thanks.
In Access you don't need ADO library to query a CSV file:
Public Function GetFirstItem(File As Scripting.File, Field As String) As String
Dim RS As DAO.Recordset, SQL As String
SQL = "SELECT TOP 1 [" & Field & "]" _
& " FROM [" & File.Name & "]" _
& " IN '" & File.ParentFolder & "'[Text;FMT=CSVDelimited;HDR=Yes];"
Debug.Print SQL
Set RS = CurrentDb.OpenRecordset(SQL)
GetFirstItem = RS(0)
RS.Close
Set RS = Nothing
End Function
Usage:
?GetFirstItem(CreateObject("Scripting.FileSystemObject").getfile("c:\path\to\your\file.csv"), "your field")

SQL Select Statement in Microsoft Access VBA - Need help inserting in Access table as block, not loop

I am trying to do a Select statement from an SQL server using an ADODB connection, within Microsoft Access VBA. The select statement is very complex with calculations and would work better to keep that to try and turn in to a connection with the DB.
I can append the data row by row, but am wondering how I could append as simple as possible as a block of data to save time/vba effort. (Lots of data!)
In order to simplify the example, I have put a basic SQL statement, but if you could review this and let me know if there is a way to append as a recordset block or what would be a better option... The code below works for pasting as a block into excel, and I would think I only need to change that commented out line's method to append in Access...
Option Private Module
Private Const DataServer = "GLSSQLMADPS2"
Private Const sqlconstring = "Driver={SQL Server};Server=" & DataServer & "; Database=PERF_MGMT_BWRSRV_PROD; Trusted_Connection=yes; Connect Timeout = 600"
Sub M2DSQLPull()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String
Dim sql As String
sql = "SELECT " & _
"Employee_Token_NR, " & _
"Null as 'Sum_Month', " & _
"1000 AS 'Data_ID', " & _
"DATEADD(m, DATEDIFF(m, 0, MIN(CALL_TS)), 0) AS 'Metric_1' " & _
"FROM PMBSED_PhoneEvaluations " & _
"GROUP BY Employee_Token_NR "
Set cn = New ADODB.Connection
cn.CommandTimeout = 120
cn.Open sqlconstring
Set rs = New ADODB.Recordset
rs.Open SqlString(i), cn, adOpenStatic, adLockReadOnly
'How I would paste in an excel spreadsheet, how do I block paste in an access database?
'ThisWorkbook.Worksheets("RawData").Cells(RowNumber, 1).CopyFromRecordset rs
RowNumber = RowNumber + rs.RecordCount
rs.Close
cn.Close
End Sub
Thank you for any assistance!
-Robert

Update Sharepoint from Excel via ADO connection - Internal name issue

I need to update a SharePoint table which has a field name with Spaces. The field name is called Tracking log
Unfortunately there are lot of reports already created that don't let me recreate this column with a different name, so I need to find a workaround to address this special name.
Lot of blogs point me to revise the internal name and check the name given when it was created, so I checked the List Setting menu for the whole URL path and see the following:
https://sales.acs.com/SMS/_layouts/15/FldEdit.aspx?List=%7B686F9AF9%2DFB64%2D4AD9%2DA268%2D19A057C432DA%7D&Field=Tracking%5Fx0020%5Flog
Below is the script I've put together which runs perfectly fine for any other field without spaces in the name, but not specifically for this one.
Dim sSQL As String
' Build the connection string
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;RetrieveIds=Yes;" & "DATABASE=" & sSHAREPOINT_SITE & ";" & "LIST=" & sDEMAND_ROLE_GUID & ";Authentication=Default;"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection.
With cn
.ConnectionString = sConn
.Open
End With
ID = "12345"
fieldName = "Tracking_x0020_log" 'Display view is "Tracking log", I've tried also with Tracking%5Fx0020%5Flog without luck
FieldValue = "Test"
'sSQL = "SELECT * FROM EMEA_SALES WHERE (APA_number='" & Format(ID, "#") & "');"
sSQL = "UPDATE EMEA_SALES SET " & fieldName & " = '" & FieldValue & "' WHERE (APA_number='" & Format(ID, "#") & "');"
rs.Open sSQL, cn, adOpenDynamic, adLockOptimistic
cn.Close
Set cn = Nothing
End Sub
The error I've got is:
No value given for one or more required parameters.
When I change the fieldname for any other without spaces is run smoothly.
Any clue will be appreciated. Thanks folks!

VBA ADO query on Excel workbook

I have the following code to retrieve data from another workbook. However I want the SQL code take into account a where clause. This where clause should be applied on one of the columns. Up till now my code works but not after adding the where clause. The column header is Cost_center. What should I write differently in my code to let the code only get data where the Cost_center column is like a certain number?
Sub newbie2() Set cn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset")
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\INP_DEPARTMENT_SOL_DEL.xlsx" & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
strSQL = "SELECT * from [sheet1$] WHERE [COST_CENTER] LIKE 5560"
rs.Open strSQL, cn, 0, 1 'cursortype = adOpenForwardOnly, locktype = adOpenReadonly
ThisWorkbook.Worksheets("Sheet2").Range("A:A").CopyFromRecordset rs
rs.Close
cn.Close
Set rs = Nothing
Set con = Nothing
End Sub
Thanks in advance,
Michiel
I'm guessing you are not getting cost centers that contain "5560" but would get cost centers that are exactly "5560."
The problem is in this line:
strSQL = "SELECT * from [sheet1$] WHERE [COST_CENTER] LIKE 5560"
The LIKE statement requires wildcard characters. For ADO, the wildcard character is %
Change the code to:
strSQL = "SELECT * from [sheet1$] WHERE [COST_CENTER] LIKE '%5560%'"
and it should work as desired.

MS Access 2007, checking current user against a table

We have a simple access database, and would like a button on a form to only be available to select members of staff. (The button has an event tied to it). I'd like to store the usernames of the staff allowed to click the button in a separate table.
What I'd like to do, is perform a simple query to see if the username exists in the table, and set the enabled state of the button depending upon the outcome.
My background is C# and SQL Server, but VBA and access are new to me, and I think I'm struggling with the quirks of this environment.
I've got the username of the logged on user in a string fOSUserName via a call to GetUserNameA in advapi32.dll, but I'm struggling with the simplest of queries to determine if the username exists in the table.
Dim strSQL As String
Dim intResult As Integer
Dim db As DAO.Database
Dim rs As Recordset
Set db = CurrentDb
strSQL = "SELECT COUNT(*) FROM [USERS] WHERE [USERS].[NAME] = '" & _
fOSUsername & "'"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If Not rs.EOF Then
intResult = rs.Fields(0)
Else
intResult = 0
End If
rs.Close
db.Close
This fails on db.OpenRecordset giving me the error
Run-time error '3061':
Too few parameters. Expected 1.
Can anyone offer some pointers?
When you continue a line in VBA, you need a space between before the line continuation character ("_"). So instead of this:
strSQL = "SELECT COUNT(*) FROM [USERS] WHERE [USERS].[NAME] = '" &_
fOSUsername & "'"
Use this:
strSQL = "SELECT COUNT(*) FROM [USERS] WHERE [USERS].[NAME] = '" & _
fOSUsername & "'"
However, as #Igor Turman pointed out, the lack of a space before the underline character should trigger a compile error. So I'm unsure what's going on but suggest you fix it anyway to avoid confusion.
I'll suggest that rather than opening a recordset, and then reading a value from that recordset, this could be handled simply with the DCount() function.
Dim strCriteria As String
strCriteria = "[USERS].[NAME] = '" & fOSUsername & "'"
Debug.Print "strCriteria: '" & strCriteria & "'"
If DCount("*", "USERS", strCriteria) = 0 Then
Debug.Print "not found"
Else
Debug.Print "found"
End IF
If your missing parameter error is because USERS is a query rather than a table, you can ask DCount() to use a table instead. Or fix the query.
Sounds like your [USERS] object is not a table but Query (with parameter). Also, if you had a syntax error like '&_'(invalid) as opposed to '& _'(valid), your database would not compile. So, if table vs query is your case, please use the following:
...
Dim rs As Recordset
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("Users")
qdf.Parameters("UserNameParameter") = fOSUsername
Set rs = qdf.OpenRecordset
...
I'm not totally familiar with the way you are using it, but I've always done it this way:
Dim sSQL As String
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=[your access db file path and name];Persist Security Info=False"
sSQL = "SELECT COUNT(*) FROM [USERS] WHERE [USERS].[NAME] = '" &_
fOSUsername & "'"
Set rs = New ADODB.Recordset
rs.Open sSQL, cn
If Not rs.EOF Then
intResult = rs.Fields(0)
Else
intResult = 0
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing