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

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

Related

Excel VBA to update an SQL date field

I'm trying up date an SQL table (Date field) with a date cell in excel and getting an error
Error #-2147217913: Operand type clah int is incompatible with Date
Connection to the database is fine.
This is the code i'm using
Private Sub CommandButton1_Click()
On Error GoTo FormLoadError
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim FromDate As Date
Dim ToDate As Date
Dim FromNumber As String
Sheet2.Range("a2:zz9999").ClearContents
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=SQL;" & _
"Initial Catalog=M2MTECLIVE;" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
FromDate = Worksheets("Parameters").Range("b4") 'Cell be contains a date in the format YYYY-MM-DD
Set rs = conn.Execute("update dbo.M2MDates set FD = " & FromDate)
conn.Close
Any ideas ?
Consider using ADO parameters via ADO command object which avoids need of concatenating and punctuating values to SQL statement:
conn.Open sConnString
' PREPARED STATEMENT WITH QMARKS ?
strSQL = "update dbo.M2MDates set FD = ?"
FromDate = Worksheets("Parameters").Range("b4")
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = strSQL
.CommandType = adCmdText
' BIND DATE PARAMETER
.Parameters.Append .CreateParameter("date_prm", adDate, adParamInput, , FromDate)
' EXECUTE ACTION QUERY (NO RECORDSET)
.Execute
End With
conn.Close
Set cmd = Nothing: Set conn = Nothing

Using Variable in SQL Query Raises ADO Error

I am trying to get a single itemcode from a SQL Server table (items) to be compared with an itemcode entered in an Excel sheet. To make this possible I have written the following VBA code in Excel 2019.
Function GetItemcodeFromSQLTable(sSQLArtikel As String) As String
Dim connection As New ADODB.connection
connection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=SQL01;Initial Catalog=110"
Dim query As String
query = "select itemcode from items where itemcode = " & sSQLArtikel
Dim rs As New ADODB.Recordset
rs.Open query, connection
connection.Close
End Function
I keep getting an error executing the line rs.open query, connection.
The purpose of this all is that I want to know if an itemcode already exists in the SQL table or not. If not, the rest of my VBA code wil create a XML file to import a new itemcode into the SQL table.
I have added a reference to "Microsoft Active X Data Objects 6.1 Library" in the VBA window.
Can anybody help me with this problem?
Many thanks.
The code I am using now is
Function CheckIfArticleCodeExistsInSQLDatabase(sSQLArtikel As String) As String
Dim query As String
Dim connection As ADODB.connection
Dim rs As ADODB.Record
Dim cmd As ADODB.Command
' PREPARED STATEMENT WITH PARAM PLACEHOLDERS
query = "select itemcode from items where itemcode = " & "'" & sSQLArtikel & "'"
' OPEN CONNECTION
Set connection = New ADODB.connection
connection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;" _
& "Data Source=SQL01;Initial Catalog=110"
' DEFINE COMMAND AND RECORDSET
Set cmd = New ADODB.Command
cmd.ActiveConnection = connection
Set rs = cmd.Execute(query, sSQLArtikel) ' BIND PARAM VALUES
' ... DO SOMETHING WITH rs
rs.Close: connection.Close
Set cmd = Nothing: Set rs = Nothing: Set connection = Nothing
End Function
When executing the command "Set rs = cmd.Execute(query, sSQLArtikel)" an errormessage is displayed "the command text is not set for the command object".
I am doing something wrong but what?
Consider the industry best practice of parameterization whenever running SQL in application layer like VBA. Doing so, you avoid the need to concatenate and punctuate variables to an SQL string.
Specifically, the missing quotes around string literals (sSQLArtikel) is your issue. With ADO Command.Execute, you can define recordsets with binded parameters.
Dim query As String
Dim connection As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
' PREPARED STATEMENT WITH PARAM PLACEHOLDERS
query = "select itemcode from items where itemcode = ?"
' OPEN CONNECTION
Set connection = New ADODB.Connection
connection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;" _
& "Data Source=SQL01;Initial Catalog=110"
' DEFINE COMMAND AND RECORDSET
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = connection
.CommandType = adCmdText
.CommandText = query
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, _
Len(sSQLArtikel), sSQLArtikel)
Set rs = .Execute
End With
' ... DO SOMETHING WITH rs
rs.Close: connection.Close
Set cmd = Nothing: Set rs = Nothing: Set connection = Nothing

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

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 ''.

Running stored procedure from Excel

I am trying to run a stored procedure from Excel. I know how to do it without using dynamic dates but I need the date range to be dynamic.
Sub TestStoredProcedure()
Dim CServer As String
Dim CDatabase As String
Dim CLogon As String
Dim CPass As String
Dim StartDate As Date
Dim EndDate As Date
Dim TStartDate As String
Dim TEndDate As String
CServer = "111111" ' Your server name here
CDatabase = "111111" ' Your database name here
CLogon = "11111111" ' your logon here
CPass = "111111" ' your password here
Dim Cmd1 As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim intTemp As Integer
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cn
Cmd1.CommandText = "callstatisticsbyQ"
Cmd1.CommandType = adCmdStoredProc
Cmd1.Parameters.Refresh
Cmd1.Parameters(0).Value = Worksheets("Sheet2").Range("A1")
Cmd1.Parameters(1).Value = Worksheets("Sheet2").Range("A2")
Cmd1.Parameters(2).Value = Worksheets("Sheet2").Range("A3")
Set rs = Cmd1.Execute()
rs.Open Cmd1
Worksheets("Procedure Export").Range("A1").CopyFromRecordset rs
Call DumpSP("prcGetData", "", "", Worksheets("Procedure Export").Range("A1"))
End Sub
I get an error saying something about user defined type not defined.
To use ADO you click Tools->references in the VBA IDE & tick "Microsoft ActiveX Data Objects" - preferably the highest version thereof.
Additionally you use cn as the connection but its not defined in that sub (assuming its not global) & you will may need to Set Cmd1.ActiveConnection = cn.
Also take a look at this, it defines the input (adParaminput) paramaters in advance rather than using .Refresh which is pretty inefficient (takes a trip to the server)
Update for example:
rem for create procedure callstatisticsbyQ (#i int, #c varchar(10)) as select 1234;
Dim cn As ADODB.Connection
Dim Cmd1 As ADODB.Command
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set Cmd1 = New ADODB.Command
Set Cmd1 = New ADODB.Command
cn.Open "Provider=SQLNCLI10;Server=1.2.3.4;Database=x;Uid=x; Pwd=x;"
Set Cmd1.ActiveConnection = cn
Cmd1.CommandText = "callstatisticsbyQ"
Cmd1.CommandType = adCmdStoredProc
Cmd1.Parameters.Append Cmd1.CreateParameter("p1", adInteger, adParamInput, , Worksheets("Sheet2").Range("A1"))
Cmd1.Parameters.Append Cmd1.CreateParameter("p2", adVarChar, adParamInput, 20, Worksheets("Sheet2").Range("A2"))
Set rs = Cmd1.Execute()
MsgBox rs(0)
rs.Close
cn.Close