Select Statement for Excel Datasource - vba

I am connected to Excel sheet, which is acting as database. I need to select some records with where condition but I am getting error:
No value given for one or more required parameters
by using below code:
Dim conn As Object
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set conn = CreateObject("ADODB.Connection")
XLName = "C:\Users\X\Desktop\rawdata.xlsx"
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" &
XLName & "';Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"
conn.Open connString
rs.Open ("SELECT * FROM [data$] where industry='Government'"), conn,
adOpenDynamic, adLockReadOnly
Sheet1.Range("A2").CopyFromRecordset rs
rs.Close
conn.Close

When you set HDR=NO the column titles from the excel table will be ignored and it will be used internal names. See older answer: c#, oledb connection string issue

Related

Lost of lengthy integers when inserting Excel VBA SQL to Access database by

I have a csv containing lengthy numbers (like 3-4 billions) which i would like to insert them into access database through ADOBD sql in excel. The code works through but all these numbers become empty when i open the Table in the Access database.
I have double checked in the Designed View in Access that the data type is "Double" in the access and I have no clue why the lengthy intergers will be lost. Can I ask for your guidance on this please? The code has been simplified but the key point is how i could do something on the INSERT INTO line to force it reading lengthy numbers into access database? Many thanks.
Dim cnn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rst As ADODB.Recordset
Dim MyConn
Dim strSQL, strSQL2, strSWL3 As String
Dim InsertDate As Date
Dim FileDate As String
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
End With
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnn
Set rst = New ADODB.Recordset
rst.Open "SELECT [Date] FROM [Text;DATABASE=C:\].[Source.csv];", cnn, adOpenDynamic, adLockOptimistic
strSQL = "INSERT INTO [Daily] "
strSQL = strSQL & "SELECT [Date] As WDate, Code, [#Sold] As QtySold"
strSQL = strSQL & " FROM [Text;DATABASE=C:\].[TargetDB.csv]"
cmd.CommandText = strSQL
cmd.Execute
Set cmd = Nothing
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing

cannot open recordset in vba

When this vba code tries to open up the recordset, I get the following error:
Run Time Error '3709'
The connection cannot be used to perform this operation. It is either closed or invalid in this context.
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
objMyConn.ConnectionString = "Driver={SQL Server};Server=localhost\SQLEXPRESS;Database=Contact;Trusted_Connection=True;"
objMyConn.Open
strSQL = "Select * from Contact where Lastname like " + Chr(39) + LastSearch + "%" + Chr(39) + " And Firstname like " + Chr(39) + FirstSearch + "%" + Chr(39)
MsgBox strSQL
objMyRecordset.Open strSQL, cnn, adOpenForwardOnly, adLockOptimistic
Add Option Explicit at the top of your module; you'll find the VBE screaming at that undeclared cnn variable.
Your recordset isn't using any open connection - as the error message is saying.
That said you can very well have single quotes inside the string literals; that Chr(39) stuff is just uselessly obfuscating the code.
Also consider using parameters instead. If you're not sure why, read about Little Bobby Tables.
Here's an example:
Option Explicit
Sub Test()
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider='SQLOLEDB';Data Source='INSTANCE NAME';Initial Catalog='DATABASE NAME';Integrated Security='SSPI';"
conn.Open
Dim sql As String
sql = "SELECT Field1 FROM dbo.TestTable WHERE Field3 LIKE '%' + ? + '%'"
Dim results As ADODB.Recordset
With New ADODB.Command
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = sql
.Parameters.Append .CreateParameter(Type:=adVarChar, Value:="foo", Size:=255)
Set results = .Execute
End With
Debug.Print results(0).Name, results(0).Value
results.Close
conn.Close
End Sub
Notice it's the Command that executes off the Connection and returns a Recordset.
Here's generic ADODB connection set up
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConnection As String
strConnection = "connectionString"
con.Open strConnection
rs.Open "SELECT * FROM Tbl", con

Write in a field's record in an Access' table

Issue :
I wrote this code which is supposed to write in a specific record of the WPRCPart field, but for some unknown reasons, nothing happens when I run it.
There are no errors though, it's just that this execution produces no result.
The data type of the WPRCPart field is Short Text.
The data type of the PartNo field is Number and its values come from a value List in Combo Box which can contains Multiple values.
Any ideas ?
Dim conn As New ADODB.Connection
Dim connStr As String
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "mypath" & "NewVersion.accdb" & ";"
conn.ConnectionString = connStr
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = "UPDATE OverViewNew Set WPRCPart = 'Yes' WHERE PartNo = 9165267"
End With
Set rs = cmd.Execute
'rs.close

Visual Basic 6.0 ADODB command to variable

Here's the code
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.CursorLocation = adUseClient
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Nirvana.mdb" & "; Persist Security Info=False;"
Set cmd = New ADODB.Command
cmd.CommandText = "Select [Last Name] From Accounts Where [First Name]=#FN"
Set cmd.ActiveConnection = conn
cmd.Parameters.Item("#FN").Value = txtFirstName.Text
cmd.Execute
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
conn.Close
How do i pass the result of this query to a variable in Visual Basic 6.0 ?
Results are stored in a Record Set, create one:
dim rs as ADODB.RecordSet
Then instead of cmd.execute use:
rs.open cmd
if not rs.eof then
''//got rows
msgbox "first row, first col=" & rs.collect(0)
...

VBA. Cant get data from .mdb file. Operation is not allowed when object is closed

Here is my problem: I need to get data from .mdb file that is on the network hard drive. I am using ADODB to connect to it, but when i try to return field value from RecordSet that i created it returns error:
Operation is not allowed when the object is closed
Here is my code:
Dim rs As New ADODB.Recordset
Dim cmd As New ADODB.Command
cmd.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ".mdb"
cmd.CommandText = SQLRequst
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
Debug.Print rs.Fields(0)
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
At the moment i tried many different types of connection. The main thing thats makes me confused is that it connects to .mdb file and also creates RecordSet but most values are set to "Operation is not allowed when object is closed"
I think the problem is with the way i am connecting and getting records sets because I use same method to connect to sql database and it works just fine.
Any help will be appreciated
*Edited : SQLRequest = "SELECT * FROM tblStack WHERE StackID=XXXXX"
Changed code to this:
Dim rs As New ADODB.Recordset
Dim conn As New ADODB.Connection
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ".mdb"
rs.Open SQLRequst, conn, adOpenForwardOnly, adLockReadOnly
Debug.Print rs.Fields(0)
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
Still debug doesn't print anything and in Locals window shows that Fields(0).Value Operation is not allowed when the object is closed
Problem was in SQLRequst string :
SQLRequest = "SELECT * FROM tblStack WHERE StackID='XXXXX'"
It needed ''.