I need to create an Access program but I am having trouble.
Here is the problem.
When I type information as below picture, all of the information should be inserted to the Listbox. 'BlendID' and 'Blend Method' are same for all element and only 'Precursor's' information change. So when I typed two item of precursor, there need to be two rows but I only get 1 data in the list box.
(Precursor2's information should be inserted in listbox but it is not working now)
Here is my code
Private Sub AddToListBlend_Click()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim strConn As String
Dim par As ADODB.Parameter 'input
'Dim introw As Integer
'On Error GoTo errorhandle
'introw = ListBlend.ListIndex + 1
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn 'open connection
If IsNull(TextRequestNo.value) Or TextRequestNo.value = "" Then
MsgBox ("Please select Request No first")
Else
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.AddBlendPrac"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
Set par = cmd.CreateParameter("#BlendID", adVarChar, adParamInput, 50, TextB10.value)
cmd.parameters.Append par
Set par = cmd.CreateParameter("#BlendMethod", adVarChar, adParamInput, 50, TextB11.value)
cmd.parameters.Append par
Set par = cmd.CreateParameter("#RequestID", adVarChar, adParamInput, 50, TextRequestNo.value)
cmd.parameters.Append par
Set par = cmd.CreateParameter("#SampleID", adVarChar, adParamInput, 50, TextB12.value)
cmd.parameters.Append par
Set par = cmd.CreateParameter("#WLocation", adVarChar, adParamInput, 50, WLocation1.value)
cmd.parameters.Append par
cmd.Execute
conn.Close 'close connection
Set conn = Nothing
Set cmd = Nothing
MsgBox "Succeeded"
List731.Requery
End If
End Sub
I am aware that I need to add Precursor2's information but I do not know how to do it. As you can see first information is inserted to the ListBox, but second one is not.
Would you please share your idea about this?
Related
I have written a stored procedure to insert the data into a table. When I execute that into SQL Server 2012 it works fine while in VBA throws error
procedure or function expects parameter #empid which was not provided
I tried to resolve with different combinations of connection strings, CommandType etc but it does not resolve. While code seems perfectly fine, please assist me to resolve it.
Stored procedure:
CREATE PROCEDURE [dbo].[spInsertDataIntoEmployee]
#empid INT,
#empname VARCHAR(20),
#empage INT,
#empsalary DECIMAL(8,2)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[employee] (empid, empname, empage, empsalary)
VALUES (#empid, #empname, #empage, #empsalary)
END
VBA code:
Private Sub Exec_StoredProcFromExcel_Click()
Dim con As ADODB.Connection
Dim res As ADODB.Recordset
Dim mobjCmd As ADODB.Command
Dim strConn As String
Dim par1 As Object
Dim par2 As Object
Dim par3 As Object
Dim par4 As Object
'Dim empname As Varchar
'Dim empage As Integer
'Dim empsalary As Single
Dim indRecordSetFields As Integer
'Dim strQuery As String
'con.Close
Set con = New ADODB.Connection
Set res = New ADODB.Recordset
Set mobjCmd = New ADODB.Command
strConn = "Driver={SQL Server Native Client 11.0};Server=localhost;Database=test;Trusted_Connection=yes;"
'strConn = "Provider=SQLOLEDB; Data Source=localhost; Initial Catalog=test; Integrated Security=SSPI;"
con.Open strConn, adOpenStatic, adLockOptimistic
Set par1 = mobjCmd.CreateParameter("#empid", adInteger, adParamInput)
Set par2 = mobjCmd.CreateParameter("#empname", adVarChar, adParamInput, 30)
Set par3 = mobjCmd.CreateParameter("#empage", adInteger, adParamInput)
Set par4 = mobjCmd.CreateParameter("#empsalary", adDouble, adParamInput)
With mobjCmd
.ActiveConnection = con
.CommandText = "Exec [dbo].[spInsertDataIntoEmployee]"
.CommandType = 1 'adCmdStoredProc=4 does not work while adCmdText=1 and adCmdUnknown=8 both work for me
.CommandTimeout = 45
.Parameters.Append par1
.Parameters("#empid").Value = 111
.Parameters.Append par2
.Parameters("#empname").Value = "majid rajih"
.Parameters.Append par3
.Parameters("#empage").Value = 34
.Parameters.Append par4
.Parameters("#empsalary").Value = 200000
'.Parameters.Append .CreateParameter("#empid", adInteger, adParamInput, 111)
'.Parameters.Append .CreateParameter("#empname", adVarChar, adParamInput, 20, "majid khan")
'.Parameters.Append .CreateParameter("#empage", adInteger, adParamInput, 30)
'.Parameters.Append .CreateParameter("#empsalary", adSingle, adParamInput, 250000)
'.Parameters.Append .CreateParameter("#empid", adInteger, adParamInput, , ThisWorkbook.Sheets("employee").Range("A2").Value)
'.Parameters.Append .CreateParameter("#empname", adVarChar, adParamInput, 20, ThisWorkbook.Sheets("employee").Range("B2").Value)
'.Parameters.Append .CreateParameter("#empage", adInteger, adParamInput, , ThisWorkbook.Sheets("employee").Range("C2").Value)
'.Parameters.Append .CreateParameter("#empsalary", adSingle, adParamInput, , ThisWorkbook.Sheets("employee").Range("D2").Value)
' repeat as many times as you have parameters
.Execute
End With
'With res
'res.CursorType = adOpenStatic
'res.LockType = adLockOptimistic
'res.Open mobjCmd 'This executed the stored proc
'End With
End Sub
You are running the command in the text mode.
Your full query is Exec [dbo].[spInsertDataIntoEmployee] which does not include any parameters.
CommandType should be adCmdStoredProc, and CommandText should be the procedure name, without exec.
.CommandType = adCmdStoredProc
.CommandText = "[dbo].[spInsertDataIntoEmployee]"
If you want to keep adCmdText, list all parameters in the query:
.CommandType = adCmdText
.CommandText = "exec [dbo].[spInsertDataIntoEmployee] #empid, #empname, #empage, #empsalary"
.CommandText = "spInsertDataIntoEmployee"
And try to send everything as nvarchar.
I'm trying to insert data from a MS Access form in to a table so I've knocked up a short function to see whether it is possible.
The function I have is this:
Function Module2() As Boolean
On Error GoTo Err_Insert
Dim adoCMD As Object
Dim adoRS As Object
Dim strSQL As String
'Define a query to INSERT a new record into the FE temp table
strSQL = "INSERT INTO [Table1] ([A1],[A2],[A3],[img] VALUES (p1,p2,p3,img);"
'Define attachment to database table specifics
Set adoCMD = CreateObject("ADODB.Command")
With adoCMD
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdText
.Parameters.Append .CreateParameter("p1", adVarChar, adParamInput, Len(Forms("Form1").Controls("text0").value), Forms("Form1").Controls("Text0").value)
.Parameters.Append .CreateParameter("p2", adBoolean, adParamInput, Len(Forms("Form1").Controls("Check2").value), Forms("Form1").Controls("Check2").value)
'.Parameters.Append .CreateParameter("p3", adVarChar, adParamInput, Len(Forms("Form1").Controls("Combo4").value), Forms("Form1").Controls("Combo4").value)
.Parameters.Append .CreateParameter("img", adLongVarBinary, adParamInput, Len(Forms("Form1").OLEBound6), Forms("Form1").Controls("OLEBound6"))
.CommandText = strSQL
Set adoRS = .Execute
End With
'Return a good return code
Module2 = True
Exit_Insert:
'Clean up the connection to the database
Set adoRS = Nothing
Set adoCMD = Nothing
Exit Function
Err_Insert:
Call MsgBox("Class: Module2, Function: Insert()")
Module2 = False
Resume Exit_Insert
End Function
when run, I get the following error:
Run-time error 3421
Application uses a value of the wrong type for the current operation
and breaks at this point:
.Parameters.Append .CreateParameter("img", adLongVarBinary, adParamInput, Len(Forms("Form1").OLEBound6), Forms("Form1").Controls("OLEBound6"))
What is the correct type for an OLEObject? I've tried several all with the same result. I cannot find which DataTypeEnum looks to be the correct type.
Thanks
When you skip parameter P3, the query will try to insert img (now the third parameter) to A3, thus the error.
I'm getting a "Run time error (13): type mismatch" error when I attempt to execute the below sproc from an after update event in Access. My sproc has the #Season as nvarchar(max) and #Year as int in the SQL (MSSQL2014). Any ideas as to the cause? I've been search all day but no joy as yet. Here is the code:
Private Sub Event_Click()
Dim cnn1 As New ADODB.Connection
Dim cmd As New ADODB.Command
Set cnn1 = New ADODB.Connection
cnn1.ConnectionString = "<connection string snipped but works OK>"
cnn1.ConnectionTimeout = 30
cnn1.Open
vSeason = Me.ComboBox1.Value
vYear = Me.ComboBox2.Value
With cmd
.ActiveConnection = cnn1
.CommandText = "dbo.StoredProcedure"
.CommandType = 4
.CommandTimeout = 0
.Parameters.Append .CreateParameter("#Season", adVarChar, adParamInput, vSeason)
.Parameters.Append .CreateParameter("#Year", adInteger, adParamInput, vYear)
End With
cnn1.Close
Set cnn1 = Nothing
Would be grateful for any pointers here. Any further info needed let me know.
I think the problem is that CreateParameter need size for adVarChar datatype before its value.
try something like:
.Parameters.Append .CreateParameter("#Season", adVarChar, adParamInput, 200, vSeason)
in your code the value vSeason is passed as size parameter,
you are passing a string as integer to CreateParameter, this is the type mismatch error
I hope this helps
I'm trying to pull data from a SQLServer database with a stored proc directly into and excel spreadsheet. I'm trying to make a dashboard that will allow the user to make a selection for the specific month they want to see and pull the data for that month. Once the data is pulled, the dashboard will automatically calculate which charts the user will see and so forth. This is my first time pulling from an ADODB connection, though, and I'm getting a problem trying to actually pull the data. I get the error "Incorrect Syntax Near 'GO'" on the line where I'm trying to copy from the recordset. Any help would be greatly appreciated.
EDIT: This is the new code. I'm now getting the run-time error 3704: Cannot perform this operation when the object is closed. It's still happening when I try to copy from the recordset.
Sub btnPullData_Click()
Dim objConn As New ADODB.Connection
Dim objRecordset As ADODB.Recordset
Dim rngTableCell As Range
Dim drpPicker As DropDown
Dim strDropVal As String
Dim objCommand As New ADODB.Command
Set rngTableCell = Range("celFirstInTable")
rngTableCell.ListObject.DataBodyRange.Rows.Delete
Set drpPicker = ThisWorkbook.Sheets("Dashboard").DropDowns("dropFis_Month")
strDropVal = Format(drpPicker.List(drpPicker.ListIndex), "mmm-yy")
objConn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=KPITRACKER;Data Source=JEFFSQL"
With objCommand
.CommandType = adCmdStoredProc
.CommandText = "DynamicPhonesSP"
.Parameters.Append .CreateParameter("#TimeSum", advarWChar, , 1, "m")
.Parameters.Append .CreateParameter("#TimeSum1", advarWChar, , 1, "d")
.Parameters.Append .CreateParameter("#TimeParam", advarWChar, , 20, strDropVal)
.Parameters.Append .CreateParameter("#RptLevel", adInteger, , , 1)
.ActiveConnection = objConn
Set objRecordset = .Execute
End With
ThisWorkbook.Sheets("Data").Range("B6").CopyFromRecordset objRecordset
objRecordset.Close
Set objRecordset = Nothing
objConn.Close
Set objConn = Nothing
End Sub
You can call stored procedures more directly: (probably some syntax issues)
Sub btnPullData_Click()
Dim lCon as New ADODB.Connection
Dim lCommand as New ADODB.Command
Dim lRecordset as ADODB.Recordset
Dim lR As Range
Dim lMonth as Variant
Set lR = Range("celFirstInTable")
lR.ListObject.DataBodyRange.Rows.Delete
lCon.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=KPITRACKER;Data Source=server"
lMonth = ThisWorkbook.Sheets("Dashboard").Shapes("dropFis_Month").ControlFormat.Value
With lCommand
.CommandType = adCmdStoredProc
.CommandText = "DynamicPhonesSP"
.Parameters.Append .CreateParameter("#TimeSum", adChar, , 1, "m")
.Parameters.Append .CreateParameter("#TimeSum1", adChar, , 1, "d")
.Parameters.Append .CreateParameter("#TimeParam", advarChar, , 10, lMonth)
.Parameters.Append .CreateParameter("#RptLevel", adInteger, , , 1)
.ActiveConnection = lCon
Set lRecordset = .Execute
End With
ThisWorkbook.Sheets("Data").Range("B6").CopyFromRecordset lRecordset
lRecordset.Close
lCon.Close
End Sub
I am attempting to create my ADODBcommand and parameters in the calligng code, so that I can pass them into a generic SQL function, but I get an error when retrieving the parameter from the list:
Dim prm As ADODB.Parameter
Dim cmd As ADODB.Command
Dim ParameterList(0) As Variant
Value = Cells(3,3).Value
Set cmd = New ADODB.Command
Set prm = cmd.CreateParameter("#Field", adVarChar, adParamInput, 50)
cmd.Parameters.Append prm
cmd.Parameters("#Field").Value = Value
ParameterList(0) = prm
Call SQLFunc(Data, SQLStr, adCmdStoredProc, cmd, ParameterList)
.
.
sub SQLFunc(ByRef Data as Variant, SQLStr as String, CommandType As ADODB.CommandTypeEnum, ByRef cmd As ADODB.Command, ParamList As Variant)
.
.
.
If cmd.CommandType <> adCmdStoredProc Then
cmd.Execute
Else
'Append the parameters
For i = LBound(ParamList, 1) To UBound(ParamList, 1)
Dim TempParam As ADODB.Parameter
Set TempParam = ParamList(i)
cmd.Parameters.Append TempParam 'Error here
Next
Set Rst = cmd.Execute
Could anyone please advise how I can achieve this?
After
ParameterList(0) = prm
ParameterList(0) is Empty, to resolve this;
set ParameterList(0) = prm
I would also strongly type this so instead of variant use Dim ParameterList(0) As ADODB.Parameter
The error you see occurs because you already append the parameter to the command before calling SQLFunc, in which you illegaly attempt to do so again. Parameter names must be unique when bound to a command.
You could remove the binding and use;
Set prm = cmd.CreateParameter("#Field", adVarChar, adParamInput, 50)
prm.Value = Value
Then prm remains independent of cmd.