Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Issues declaring an SQL Connection in VBA Excel?
- Private Sub CommandButton1_Click()
- 'This sub-routine defines an ADOBD command to return variables to VBA from SQL Stored Procedures.
- 'The ADODB command executes a Stored Procedure on the SQL Server (cmd.CommandText = [Stored Procedure Name])
- 'Input requirements from the Stored procedure are declared as variants at the start of the sub-routine.
- Dim cnt As ADODB.Connection
- Dim rst As ADODB.Recordset
- Dim cmd As ADODB.Command
- Dim stCon As String 'SQL Connection string
- Dim stProcName As String 'Stored Procedure name
- 'Declare variables for Stored Procedure
- Dim user As String
- Dim password As String
- Dim companyId As Integer
- 'Set ADODB requirements
- Set cnt = New ADODB.Connection
- Set rst = New ADODB.Recordset
- Set cmd = New ADODB.Command
- 'Define database connection string
- stCon = "Provider=SQLOLEDB.1;"
- stCon = stCon + "Password=Cosin123;"
- stCon = stCon + "Persist Security Info=True;"
- stCon = stCon + "User ID=easywork;"
- stCon = stCon + "Initial Catalog=EasyWorkDesenvolvimento;"
- stCon = stCon + "Data Source=192.168.0.21;"
- stCon = stCon + "Use Procedure for Prepare=1;"
- stCon = stCon + "Auto Translate=True;"
- stCon = stCon + "Packet Size=4096;"
- stCon = stCon + "Workstation ID=WEBMOBILE04;"
- stCon = stCon + "Use Encryption for Data=False;"
- stCon = stCon + "Tag with column collation when possible=False;"
- 'Open database connection
- cnt.ConnectionString = stCon
- cnt.Open
- ' Defines the stored procedure commands
- stProcName = "SP_GE_EFFECTUSERLOGON" 'Define name of Stored Procedure to execute.
- cmd.CommandType = adCmdStoredProc 'Define the ADODB command
- cmd.ActiveConnection = cnt 'Set the command connection string
- cmd.CommandText = stProcName 'Define Stored Procedure to run
- 'set parameters to be executed
- user = UserForm2.TextBox1.Text
- password = UserForm2.TextBox2.Text
- Set prm = cmd.CreateParameter("@user", adVarChar, adParamInput, 50, user)
- Set prm1 = cmd.CreteParameter("@password", adVarChar, adParamInput, 50, password)
- 'Append parameters
- With cmd
- .Parameters.Append prm, prm1
- End With
- 'Execute stored procedure and return to a recordset
- rst.Open cmd.Execute
- myReturn = rst.Fields("myVariable").Value
- Call Sub-Routine_That_Uses_The_Returned_Data
- 'Close database connection and clean up
- If CBool(rst.State And adStateOpen) = True Then rst.Close
- Set rst = Nothing
- If CBool(cnt.State And adStateOpen) = True Then cnt.Close
- Set cnt = Nothing
- End Sub
Add Comment
Please, Sign In to add comment