Write/update data via ADO to closed Excel workbook - excel

I'm trying to change the number in a closed Excel workbook using ADO. I found the below code written in 2015 by L42. But the procedure stops with the error "No value given for one or more required parameters". I can't find where something is missing!
Sub ChangeNum()
Dim con As ADODB.Connection, rec As ADODB.Recordset
Dim sqlstr As String, datasource As String
Set con = New ADODB.Connection: Set rec = New ADODB.Recordset
datasource = "D:\DropBox\TraderShare\TraderNum.xlsx"
Dim sconnect As String
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & datasource & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
con.Open sconnect
sqlstr = "UPDATE [Sheet1$] SET [Number] = ""16900"" WHERE [ID] = INum"
rec.Open sqlstr, con, adOpenUnspecified, adLockUnspecified 'adLockOptimistic , adOpenStatic, adLockReadOnly
con.Close
Set rec = Nothing: Set con = Nothing
End Sub
Grateful for any help!

I found the fault! The sqlstr should be written:
sqlstr = "UPDATE [Sheet1$] SET [Number] = ""16900"" WHERE [ID] = ""INum"""
It's the exclamation marks that matters! I don't know why it's required in this way, if the exclamation marks are required to concatenate different parts of the string. But they look to be out of sequence, there's 1 too much in the end!

The usual reason for this error is a missing or misspelled value. I would go over the SQL statement specifically and see whats off

Related

Retrieve all of query containing semi-colons

I'm trying to pull data from SQL via an ADODB recordset in VBA. I'm struggling to get results from each part of a SQL query when it contains semi-colons. Wondering if there's any way to do this without splitting my query into separate queries (to remove the semi-colon issue) and using separate recordsets for each.
See below for a simple example. When I run it, F2=1, G2=Failed - I want F2=1, G2=2.
' Sub to test using semi-colons in SQL queries
Sub getDataSimple0(server As String, database As String)
' Initialise variables
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open Connection using Windows Authentication
con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Trusted_connection=Yes;Integrated Security=SSPI;Persist Security Info=True;"
con.Open
' Open recordset
rs.Open "SELECT 1; SELECT 2", con
' Add data to worksheet
Range("F2").CopyFromRecordset rs
rs.NextRecordset
If rs.State > adStateClosed Then
Range("G2").CopyFromRecordset rs
Else
Range("G2").Value = "Failed"
End If
' Close connection
con.Close
End Sub
I would go about it by doing something like the below.
' Sub to test using semi-colons in SQL queries
Sub getDataSimple0(server As String, database As String)
' Initialise variables
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim SQL_String As String
Dim SQL_Array() As String
Dim i As Integer
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open Connection using Windows Authentication
con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Trusted_connection=Yes;Integrated Security=SSPI;Persist Security Info=True;"
con.Open
'Multiple queries
SQL_String = "SELECT 1; SELECT 2"
'Split into array
SQL_Array = Split(SQL_String, ";")
'Add data to worksheet
For i = LBound(SQL_Array) To UBound(SQL_Array)
rs.Open SQL_Array(i), con
Range("F2").Offset(0, i).CopyFromRecordset rs
Next i
' Close connection
con.Close
End Sub
Here I take the multiple queries and split them into an array that I loop over. Assuming that you want the ouptut in columns from column F and onward.
I believe you need to set the rs to the result of NextRecordset, so the code looks like this:
' Sub to test using semi-colons in SQL queries
Sub getDataSimple0(server As String, database As String)
' Initialise variables
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open Connection using Windows Authentication
con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Trusted_connection=Yes;Integrated Security=SSPI;Persist Security Info=True;"
con.Open
' Open recordset
rs.Open "SELECT 1; SELECT 2", con
' Add data to worksheet
Range("F2").CopyFromRecordset rs
Set rs = rs.NextRecordset
If rs.State > adStateClosed Then
Range("G2").CopyFromRecordset rs
Else
Range("G2").Value = "Failed"
End If
' Close connection
con.Close
End Sub

Read Excel file into ADODB recordset

I have an Excel VBA application that reads information from other excel files using ADODB recordsets. This application was working just fine, but a company software update just broke it (I guess, can't explain otherwise).
Copied below is a stripped down version that replicates the error I'm getting (also shown below). I've tried to review the many posts that reference Microsoft.Jet.OLEDB.4.0, but I'm not sure this is related. They all reference a specific error that I'm not seeing.
The identified error is caused by the CN.Open command. Thanks to comment from Matt'sMug, I have determined that I can execute the connection with no issue, provided the subject workbook is already open in Excel. If it is closed (as it should be), the error returns. Any ideas?
Public Sub GetExcelContent()
Dim Excelbook As String
Dim CN As ADODB.Connection, RS As ADODB.Recordset
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Excelbook = Sheets(1).Cells(4, 3)
Set CN = CreateObject("ADODB.Connection")
Set RS = CreateObject("ADODB.Recordset")
CN.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source= " & Excelbook & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
RS.Open "SELECT * FROM [M2_F$]", _
CN, adOpenStatic, adLockOptimistic, adCmdText
End Sub
So, I have not figured out why the previous provider has ceased to work. However, I was able to switch to an alternate that works just as well. The coding is a little cleaner as well, so I'm happy. Here's my new protocol:
Dim CN as New ADODB.Connection
Dim RS as New ADODB.Recordset
Cstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & Excelbook & _
& "; Extended Properties='Excel 12.0 Xml;HDR=YES';"
CN.Open Cstring
RS.Open "SELECT * FROM [M3_F$]", CN, adOpenStatic, adLockOptimistic, adCmdText

Error when running a parameter query from access 2007 in excel vba

I'm trying to run a query in an Access 2007 database from an Excel 2007 VBA script. The Access query has parameters called "Year" and "Month".
I'm trying to get the following code to work:
Sub RunMyQuery()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dbPath As String
Dim stQRY As String
Dim stCon As String
Dim cmd As New ADODB.Command
Dim prmYear As New ADODB.Parameter
Dim prmMonth As New ADODB.Parameter
dbPath = "<PATH_TO_MY_DB>"
stCon = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & dbPath & ";"
cn.Open (stCon)
cn.CursorLocation = adUseClient
Set cmd.ActiveConnection = cn
Set prmYear = cmd.CreateParameter("Year", adNumeric, adParamInput, , 2011)
Set prmMonth = cmd.CreateParameter("Month", adNumeric, adParamInput, , 5)
cmd.Parameters.Append prmYear
cmd.Parameters.Append prmMonth
cmd.CommandText = "SELECT * FROM [Month_Totals]"
cmd.CommandType = adCmdTable
Set rs = cmd.Execute
Sheets("Sheet1").Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
When I run this, the code stops on "cmd.Execute" with
Run-time error '-214217900 (80040e14)':
Syntax error in FROM clause.
What am I getting wrong?
The command text seems simple enough to me. Am I missing something there?
Am I misusing the parameters functionality of ADODB.Command? I don't think that's the problem here, because I've tried running this same script with a non-parametrized query substituted for Month_Totals, and gotten the same error.
I believe The parameters are only for use when you are using a saved query in access. I would solve your problem by moving the parameters into the SQL statment.
Change
"SELECT * FROM [Month_Totals]"
to
"SELECT * FROM [Month_Totals] WHERE Year = 2011 AND Month = 5"
The reason that this is returning an error is that command type is set to adCmdtable, but the command does not reference a table, it references an SQL string, so:
cmd.CommandType = adCmdText
Next, in order to return specific data, you need to include a WHERE clause, with field names in the correct order for the parameters:
cmd.CommandText = "SELECT * FROM [Month_Totals] Where [Year]=? AND [Month]=?"

asp and ms-access db - how to import data from xls file

i want to allow the user to upload xls file with 9 columns and unlimited number of rows.
i will run over everyline and insert the data to the db
how do i read the xls file?
You can read the XLS by opening an ADO recordset which pulls in the spreadsheet's data.
This example reads data from a spreadsheet named Billing Summary which includes column names in the first row..
Public Sub ReadSpreadsheet()
Const cstrFolder As String = "C:\Access\webforums"
Const cstrFile As String = "ExampleFinance.xls"
Dim strConnect As String
Dim strSql As String
Dim cn As Object
Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
cstrFolder & Chr(92) & cstrFile & _
";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strConnect
strSql = "SELECT * FROM [Billing Summary$] WHERE SomeField Is Not Null;"
rs.Open strSql, cn
Do While Not rs.EOF
'* do something with each row of data *'
'Debug.Print rs!SomeField '
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If that particular connection string doesn't work for you, look at other examples of Excel connection strings at Connection strings for Excel
Edit: That example works in Access. But you said ASP. I think it will work there, too, if you drop the data types from the variable and constant declarations: Dim strSql instead of Dim strSql As String
Example of using an SQL statement to update Access from Excel.
Set cn = CreateObject("ADODB.Connection")
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\docs\dbto.mdb"
cn.Open scn
sSQL = "SELECT * INTO NewTable FROM "
sSQL = sSQL & "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\Docs\From.xls].[Sheet1$]"
cn.Execute sSQL, recs
MsgBox recs
In C#, I had to load an excel spreadsheet to a DataSet - this got me there...
Code Project Example
I used Option 1 - the Preferred method! Hope this helps...
Mike

ADODB recordset in VBA says excel field is empty when it's not

I have an excel sheet I need to import in my Access database.
The sheet looks like this:
DATE RECEPTION DENOMINATION ITEM N° QUANTITE RECUE
06/01/2010 DVD-Sex & the City PCR-PA21550167 5
06/01/2010 DVD-Avatar Natie 2 PCR-PA21550209 10
I then transfer this file into the database using adodb:
Dim rs2 As New ADODB.Recordset
Dim cnn2 As New ADODB.Connection
Dim cmd2 As New ADODB.Command
Dim intField As Integer
Dim strFile As String
strFile = fncOpenFile
If strFile = "" Then Exit Sub
With cnn2
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & strFile& "; " & "Extended Properties=Excel 8.0"
.Open
End With
Set cmd2.ActiveConnection = cnn2
cmd2.CommandType = adCmdText
cmd2.CommandText = "SELECT * FROM [PCR$]"
rs2.CursorLocation = adUseClient
rs2.CursorType = adOpenDynamic
rs2.LockType = adLockOptimistic
rs2.Open cmd2
While Not rs2.EOF
strNaam = rs2.Fields(3).Value
Loop
Now my problem: certain fields have text in them.
The field value should then be item0001, but it's reportedly NULL
When the field has a regular number it works fine.
The strange thing is: there are other text fields in the sheet and they work FINE.
Be more specific in your Extended Properties portion (and don't omit inner quotes there).
In particular, try Extended Properties="Excel 8.0;HDR=Yes;IMEX=1" to allow mixed numbers&text data.
More details at http://connectionstrings.com/.

Resources