Write Multiple Rows in EXCEL (VB) to SQL Table - sql-server

Would like to be able to write all rows that have data in them to SQL table, with the below I can only export the 1st row. If I add more rows of data and click the Export Button I will only send the first row. Can some one help me script my request?
Sub Button1_Click()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim strSQL As String
strSQL = "INSERT INTO dbo.TimeLog" & _
"(EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) " & _
"VALUES (?,?,?,?,?,?,?);"
Set conn = New ADODB.Connection
conn.Open "Provider=SQLOLEDB;Data Source=db\db1;Initial Catalog=Table1;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = strSQL
iRowNo = 2
With Sheets("Sheet1")
'Loop until empty cell in EventDate
Do Until .Cells(iRowNo, 1) = ""
cmd.Parameters.Append _
cmd.CreateParameter("pEventDate", adVarChar, adParamInput, 8, .Cells(iRowNo, 1))
cmd.Parameters.Append _
cmd.CreateParameter("pID", adInteger, adParamInput, , .Cells(iRowNo, 2))
cmd.Parameters.Append _
cmd.CreateParameter("pDeptCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 3))
cmd.Parameters.Append _
cmd.CreateParameter("pOpCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 4))
cmd.Parameters.Append _
cmd.CreateParameter("pStartTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 5))
cmd.Parameters.Append _
cmd.CreateParameter("pFinishTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 6))
cmd.Parameters.Append _
cmd.CreateParameter("pUnits", adInteger, adParamInput, , .Cells(iRowNo, 7))
cmd.Execute
iRowNo = iRowNo + 20
Loop
MsgBox "Success!"
End With
conn.Close
Set conn = Nothing
End Sub

Related

How to find duplicate entries in table (SQL Server) in VBA [duplicate]

This question already has answers here:
INSERT VALUES WHERE NOT EXISTS
(6 answers)
Closed 9 months ago.
I am inserting records into a SQL Server table from an Excel sheet through VBA code with the same column headers as in the SQL Server table.
There are 4 columns in the SQL Server table which should not have values to be inserted that already exist. Those columns on the table are SF Payroll ID, Unity Payroll Element Name, ICP/LMC Element Code & ICP/LMC Element Name.
Every time each row is being inserted from the Excel file the code needs to check, that inserting values for columns SF Payroll ID + Unity Payroll Element Name + ICP/LMC Element Code + ICP/LMC Element Name does not already exist.
If the row contains the same value that already exists on the column then that row should be rejected from being uploaded to the SQL Server table and the rest of the rows should be uploaded.
Below is my code which uploads the records into the SQL Server table. Kindly suggest how to code in VBA to validate this.
Private Sub PushToDB_Click()
Dim conn As ADODB.connection
Dim connString As String
connString = "Provider=SQLOLEDB;Server=DEEPAKSQL;Database=Workload;User Id=DHARMA;Password= ********"
Set conn = New ADODB.connection
conn.Open connString
Dim rowCountsheet As Integer
rowCountsheet = ActiveSheet.UsedRange.Rows.Count
Dim tempisheet As Integer
tempisheet = 2
Dim shsheet As Worksheet
Set shsheet = ThisWorkbook.Worksheets("Data copied")
On Error GoTo CleanFail
conn.BeginTrans
Dim rowCount As Integer
rowCount = ActiveSheet.UsedRange.Rows.Count
Dim tempi As Integer
tempi = 2
Dim sql As String
sql = " INSERT INTO [dbo].[ELEMENT_INFO] ([DB_Upload_Action_Key],[Account_Client_Customer_Name],[SF_Account_ID],[Payroll],[SF_Payroll_ID],[Record_Creation_Date],[Record_Creation_Time_At],[Record_Creation_Guardian_Name],[Record_Last_Modified_Date],[Record_Last_Modified_Time_At],[Record_Last_Modified_Guardian_Name]," _
& "[Unity_Payroll_Element_Name],[Element_Description],[Element_Status],[Element_Type]," _
& "[Element_Input_Classification],[Element_Input_Type],[Element_Frequency]," _
& "[ICP_Or_LMC_Element_Code],[ICP_Or_LMC_Element_Name],[Source_Of_Data_Input_HCM_Integration_EUT_T_A_Other],[GL_Code_Debit],[GL_Code_Credit],[GL_Account_Name],[Comments])" & _
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Data copied")
Dim pctDone As Single
Dim iLabelWidth As Integer
iLabelWidth = 240
Do Until tempi = rowCount + 1
mapping_upload.Hide
frmProgressForm.Show
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = sql
cmd.Parameters.Append cmd.CreateParameter("DB_Upload_Action_Key", adVarChar, adParamInput, 100, sh.Cells(tempi, 1).Value)
cmd.Parameters.Append cmd.CreateParameter("Account_Client_Customer_Name", adVarChar, adParamInput, 250, sh.Cells(tempi, 2).Value)
cmd.Parameters.Append cmd.CreateParameter("SF_Account_ID", adVarChar, adParamInput, 250, sh.Cells(tempi, 3).Value)
cmd.Parameters.Append cmd.CreateParameter("SF_Payroll_ID", adVarChar, adParamInput, 250, sh.Cells(tempi, 6).Value)
cmd.Parameters.Append cmd.CreateParameter("Record_Creation_Date", adDBDate, adParamInput, 100, dateLabel.Caption) 'sh.Cells(tempi, 10).Value)
cmd.Parameters.Append cmd.CreateParameter("Record_Creation_Time_At", adDBTime, adParamInput, 100, timeLabel.Caption) 'sh.Cells(tempi, 11).Value)
cmd.Parameters.Append cmd.CreateParameter("Record_Creation_Guardian_Name", adVarChar, adParamInput, 100, TextBox1.Text) 'sh.Cells(tempi, 12).Value)
cmd.Parameters.Append cmd.CreateParameter("Record_Last_Modified_Date", adDBDate, adParamInput, 100, dateLabel.Caption) 'sh.Cells(tempi, 13).Value)
cmd.Parameters.Append cmd.CreateParameter("Record_Last_Modified_Time_At", adDBTime, adParamInput, 100, timeLabel.Caption) 'sh.Cells(tempi, 14).Value)
cmd.Parameters.Append cmd.CreateParameter("Record_Last_Modified_Guardian_Name", adVarChar, adParamInput, 100, TextBox1.Text) 'sh.Cells(tempi, 15).Value)
cmd.Parameters.Append cmd.CreateParameter("Unity_Payroll_Element_Name", adVarChar, adParamInput, 3500, sh.Cells(tempi, 16).Value)
cmd.Parameters.Append cmd.CreateParameter("Element_Description", adVarChar, adParamInput, 5000, sh.Cells(tempi, 17).Value)
cmd.Parameters.Append cmd.CreateParameter("Element_Status", adVarChar, adParamInput, 500, sh.Cells(tempi, 18).Value)
cmd.Parameters.Append cmd.CreateParameter("Element_Type", adVarChar, adParamInput, 5000, sh.Cells(tempi, 19).Value)
cmd.Parameters.Append cmd.CreateParameter("Element_Input_Classification", adVarChar, adParamInput, 5000, sh.Cells(tempi, 32).Value)
cmd.Parameters.Append cmd.CreateParameter("Element_Input_Type", adVarChar, adParamInput, 5000, sh.Cells(tempi, 33).Value)
cmd.Parameters.Append cmd.CreateParameter("Element_Frequency", adVarChar, adParamInput, 5000, sh.Cells(tempi, 39).Value)
cmd.Parameters.Append cmd.CreateParameter("ICP_Or_LMC_Element_Code", adVarChar, adParamInput, 5000, sh.Cells(tempi, 40).Value)
cmd.Parameters.Append cmd.CreateParameter("ICP_Or_LMC_Element_Name", adVarChar, adParamInput, 5000, sh.Cells(tempi, 41).Value)
cmd.Parameters.Append cmd.CreateParameter("Source_Of_Data_Input_HCM_Integration_EUT_T_A_Other", adVarChar, adParamInput, 5000, sh.Cells(tempi, 42).Value)
cmd.Parameters.Append cmd.CreateParameter("GL_Code_Debit", adVarChar, adParamInput, 5000, sh.Cells(tempi, 43).Value)
cmd.Parameters.Append cmd.CreateParameter("GL_Code_Credit", adVarChar, adParamInput, 5000, sh.Cells(tempi, 44).Value)
cmd.Parameters.Append cmd.CreateParameter("GL_Account_Name", adVarChar, adParamInput, 5000, sh.Cells(tempi, 45).Value)
cmd.Parameters.Append cmd.CreateParameter("Comments", adVarChar, adParamInput, 8000, sh.Cells(tempi, 50).Value)
cmd.Execute
tempi = tempi + 1
pctDone = (tempi - 1) / rowCount
frmProgressForm.lblProgress.Width = iLabelWidth * pctDone
frmProgressForm.FrameProgress.Caption = Format(pctDone, "0%")
DoEvents
Loop
Unload frmProgressForm
MsgBox "Data Loaded Successfully to T-1 DataBase", vbInformation, "SDD04 - Commit Transaction, Okay!"
mapping_upload.Show
conn.CommitTrans
CleanExit:
conn.Close
Exit Sub
CleanFail:
conn.RollbackTrans
MsgBox "Input file error either value exceeds or having wrong type. Transaction was rolled back. " & Err.Description, vbCritical, "SDD04 - Input error"
Unload frmProgressForm
Debug.Print Err.Number, Err.Description
Resume CleanExit
End Sub
You are using a loop to reach every row, and building the INSERT INTO statement. That's right, but I don't see any code trying to check what you need: If that row already exists before inserting it.
So, what you need is to check, for every row, if it exists in your SQL table before inserting it. As you have to do it for every row, think that the first thing you should do in the loop before build the INSERT statement, is to build the SELECT statement to do the check, and then, depending on the result, you will do the INSERT or not.
I suppose you can build a SELECT statement from VBA if you are able to build an INSERT statement. Otherwise you can ask for help about it.
ADDED: 2022-05-20
Here is a code snippet that may help you with the SELECT statement.
Private Sub Test()
Dim cnn As New ADODB.Connection
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
Dim ConnectionString As String
Dim strSql As String
ConnectionString = "Provider=SQLOLEDB;Server=DEEPAKSQL;Database=Workload;User Id=DHARMA;Password= ********"
strSql = "SELECT * FROM [dbo].[ELEMENT_INFO] WHERE [SF Payroll ID]=" & Value1 & " AND [Unity Payroll Element Name]='" & Value2 & "' AND ..."
rst.CursorLocation = adUseClient ' Client-side cursor
rst.Open strSql, cnn
If Not rst.RecordCount > 0 Then
'Not Exists -> Do the Insert
Else
'Exists -> Don't do the Insert
End If
rst.Close
Set rst = Nothing
End Sub

"The precision is invalid" during insert from stored procedure?

I am trying to insert values ​​from VB6 to SQL Server with a stored procedure but when I want to execute the process, I get this error:
The precision is invalid
I have already changed so many times the way that I try to enter them that I no longer know what to do.
This is the code in VB6
Dim strSQL As String
strSQL = "INSERT INTO FacturasPendientes (IdFactura,FechaFactura,CodigoProveedor,NombreProveedor," _
& " SubTotal,Iva,Total,FechaVencimiento,DiasDescuento,DescProntoPago,Pagado) VALUES (?,?,?,?,?,?,?,?)"
Dim CmdCont As ADODB.Command
Set CmdCont = New ADODB.Command
With CmdCont
Set .ActiveConnection = Cnn
.CommandType = adCmdStoredProc
.CommandText = "sp_FacturasCompras"
.Parameters.Append CmdCont.CreateParameter("#IdFactura", adVarChar, adParamInput, 50, TxtFactura.Text)
.Parameters.Append CmdCont.CreateParameter("#FechaFactura", adDate, adParamInput, 50, dtpFactura.Value)
.Parameters.Append CmdCont.CreateParameter("#CodigoProveedor", adVarChar, adParamInput, 50, TxtCodigoProveedor.Text)
.Parameters.Append CmdCont.CreateParameter("#NombreProveedor", adVarChar, adParamInput, 100, txtProveedor.Text)
.Parameters.Append CmdCont.CreateParameter("#SubTotal", adNumeric, adParamInput, 18, Round(Val(m_Subtotal), 2))
.Parameters.Append CmdCont.CreateParameter("#Iva", adNumeric, adParamInput, 18, Round(Val(m_Iva), 2))
.Parameters.Append CmdCont.CreateParameter("#Total", adNumeric, adParamInput, 18, Round(Val(m_Total), 2))
.Parameters.Append CmdCont.CreateParameter("#FechaVencimiento", adDate, adParamInput, 50, FechaFinal)
.Parameters.Append CmdCont.CreateParameter("#DiasDescuento", adVarChar, adParamInput, 50, txtDias.Text)
.Parameters.Append CmdCont.CreateParameter("#DescProntoPago", adVarChar, adParamInput, 50, txtDescuento.Text)
.Parameters.Append CmdCont.CreateParameter("#Pagado", adBigInt, adParamInput, chkPago.Value)
.Prepared = True
.Execute
End With
MsgBox "Se Grabaron los datos"
And the stored procedure is this:
ALTER PROCEDURE [dbo].[sp_FacturasCompras]
-- agregamos los valores de la consulta
#IdFactura VARCHAR(50),
#FechaFactura DATE,
#CodigoProveedor VARCHAR(50),
#NombreProveedor VARCHAR(100),
#SubTotal NUMERIC(18),
#Iva NUMERIC(18),
#Total NUMERIC(18),
#FechaVencimiento DATE,
#DiasDescuento VARCHAR(50),
#DescProntoPago VARCHAR(50),
#Pagado BIGINT
AS
BEGIN
INSERT INTO FacturasPendientes (IdFactura, FechaFactura, CodigoProveedor, NombreProveedor,
SubTotal, Iva, Total, FechaVencimiento,
DiasDescuento, DescProntoPago, Pagado)
VALUES (#IdFactura, #FechaFactura, #CodigoProveedor, #NombreProveedor,
#SubTotal, #Iva, #Total, #FechaVencimiento,
#DiasDescuento, #DescProntoPago, #Pagado)
END
The easiest way to call a stored procedure is to use Cnn connection object like this
Cnn.sp_FacturasCompras TxtFactura.Text, dtpFactura.Value, _
TxtCodigoProveedor.Text, txtProveedor.Text, _
Round(Val(m_Subtotal), 2), Round(Val(m_Iva), 2), _
Round(Val(m_Total), 2), FechaFinal, txtDias.Text, _
txtDescuento.Text, chkPago.Value
. . . which looks like an ordinary method call on the Cnn object.
If you have to use ADODB.Command then best would be to use some helper function for initializing ADODB.Parameter instances and ADODB.Command instances like this
Option Explicit
Private m_Subtotal As Double
Private m_Iva As Double
Private m_Total As Double
Private Sub Form_Load()
Dim oCmd As ADODB.Command
Set oCmd = InitCommandHelper("sp_FacturasCompras", _
InitParamHelper(TxtFactura.Text, adVarChar, 50), _
InitParamHelper(dtpFactura.Value, adDBDate), _
InitParamHelper(TxtCodigoProveedor.Text, adVarChar, 50), _
InitParamHelper(txtProveedor.Text, adVarChar, 100), _
InitParamHelper(Round(Val(m_Subtotal), 2), adDecimal, Precision:=18, NumericScale:=2), _
InitParamHelper(Round(Val(m_Iva), 2), adDecimal, Precision:=18, NumericScale:=2), _
InitParamHelper(Round(Val(m_Total), 2), adDecimal, Precision:=18, NumericScale:=2), _
InitParamHelper(FechaFinal, adVarChar, 50), _
InitParamHelper(txtDias.Text, adVarChar, 50), _
InitParamHelper(txtDescuento.Text, adVarChar, 50), _
InitParamHelper(chkPago.Value, adBigInt))
Debug.Print oCmd.Parameters.Count
End Sub
Public Function InitCommandHelper( _
ByVal sStoredProc As String, _
ParamArray Params() As Variant) As ADODB.Command
Const FUNC_NAME As String = "InitCommandHelper"
Dim lIdx As Long
On Error GoTo EH
Set InitCommandHelper = New ADODB.Command
With InitCommandHelper
If InStr(sStoredProc, ".") > 0 Then
.CommandText = sStoredProc
Else
.CommandText = "dbo." & sStoredProc
End If
.CommandType = adCmdStoredProc
.Parameters.Append .CreateParameter("RetVal", adInteger, adParamReturnValue)
lIdx = LBound(Params)
Do While lIdx <= UBound(Params)
.Parameters.Append Params(lIdx)
lIdx = lIdx + 1
Loop
End With
Exit Function
EH:
Debug.Print "Critical error: " & Err.Description & "[Form1." & FUNC_NAME & "]", Timer
End Function
Public Function InitParamHelper( _
ByVal vValue As Variant, _
ByVal eType As ADODB.DataTypeEnum, _
Optional ByVal Size As Long, _
Optional Direction As ADODB.ParameterDirectionEnum = adParamInput, _
Optional ByVal Name As String, _
Optional ByVal Precision As Long, _
Optional ByVal NumericScale As Long) As ADODB.Parameter
Const FUNC_NAME As String = "InitParamHelper"
Const DBL_NUM_LIMIT As Double = 10# ^ 12 ' 922337203685477#
Const EMPTY_GUID As String = "{00000000-0000-0000-0000-000000000000}"
On Error GoTo EH
Select Case eType
Case adVarChar, adVarWChar, adChar, adWChar
'--- trim varchar params'
If Not IsNull(vValue) And Not IsEmpty(vValue) Then
vValue = Left$(vValue, Size)
End If
Case adLongVarChar, adLongVarWChar, adLongVarBinary
'--- fix default size for BLOB params'
If Size = 0 Then
Size = -1
End If
Case adDBTimeStamp
If CDate(vValue) = CLng(CDate(vValue)) Then
eType = adDBDate
ElseIf CLng(CDate(vValue)) = 0 Then
eType = adDBTime
Else
eType = adDate
End If
Case adNumeric, adDecimal, adCurrency
'--- numeric range'
If IsNumeric(vValue) Then
If vValue > DBL_NUM_LIMIT Then
vValue = DBL_NUM_LIMIT
ElseIf vValue < -DBL_NUM_LIMIT Then
vValue = -DBL_NUM_LIMIT
End If
End If
Case adGUID
If Direction = adParamInput Then
If IsEmpty(vValue) Then
vValue = EMPTY_GUID
End If
End If
End Select
Set InitParamHelper = New ADODB.Parameter
InitParamHelper.Name = Name
InitParamHelper.Type = eType
InitParamHelper.Direction = Direction
InitParamHelper.Size = Size
InitParamHelper.Value = vValue
If Precision > 0 Then
InitParamHelper.Precision = Precision
End If
If NumericScale > 0 Then
InitParamHelper.NumericScale = NumericScale
End If
Exit Function
EH:
Debug.Print "Critical error: " & Err.Description & "[Form1." & FUNC_NAME & "]", Timer
Set InitParamHelper = Nothing
End Function
Note that NUMERIC(18) gets parsed as NUMERIC(18, 0) which has 0 digits after floating-point but you use Round(..., 2) for these params so probably an error. Just use NUMERIC(18, 2) or evern better DECIMAL(19, 2) as precision 18 and precision 19 use the same 5 bytes for storage.
Also note that sp_ prefix is reserved for system stored procedures, don't use it for user-defined stored procedures. You have to come up with different prefix like usp_ for sp (without underscore).
I suspect the issue is with the adNumeric columns. Try code like the following:
Dim p As Parameter
With CmdCont
Set p = .CreateParameter("#SubTotal", adNumeric, adParamInput)
p.Precision = 18
p.NumericScale = 2
p.Value = Round(Val(m_Subtotal), 2)
.Parameters.Append p
End With
You can adjust the precision and scale as needed.

VB6 More than 10 parameters for stored procedure

I have problem in vb6 when I'm trying to insert parameters that are more than 10, 9 below are fine.
When I try from '#1' to '#9' its fine, the output will be strsql = '1st value'...'9th value', but when I with 10 parameter it outputs strsql = '#1'...'#10'
Set rsOR = New ADODB.Recordset
strSql = SQLParams("DB..sp_Insert '#1','#2','#3','#4','#5','#6','#7','#8','#9','#10'", cbPayor.Text, "COLLECTION", txtORCol.Text, dtCol.Value, UserID, CollectionType, txtAmountCol.Text, "PHP", dtColCash.Value, txtCheque.Text)
clsSession.Execute strSql, rsOR
No error using
'#1'...'#9'
FROM: strSql = SQLParams("DB..sp_Insert '#1',...,'#9'", cbPayor.Text, "COLLECTION")
OUTPUTS: strsql "DB..sp_Insert 'text here',.... ,'COLLECTION'
Error using
'#1'...'#10'
FROM: strSql = SQLParams("DB..sp_Insert '#1',...,'#10'", cbPayor.Text, "COLLECTION")
OUTPUTS: strsql "DB..sp_Insert '#1'...'#10'
After a bit of googling I found this (there should be no 9 field limit):
Dim strSQL As String
Dim cmd As New ADODB.Command
strSQL = "UPDATE MyTable SET " & vbNewLine _
& " NEEDS_ID = #NEEDS_ID, " & vbNewLine _
& " OBJ_ID = #OBJ_ID, " & vbNewLine _
& " OBJ_COMMENTS = #OBJ_COMMENTS, " & vbNewLine _
& " TIME21_ID = #TIME21_ID, " & vbNewLine _
& " WHERE ID = #WHEREID"
With cmd
.ActiveConnection = Cn
.CommandText = strSQL
.Parameters.Append .CreateParameter("#NEEDS_ID", adInteger, adParamInput, 2, 12)
.Parameters.Append .CreateParameter("#OBJ_ID", adInteger, adParamInput, 2, 23)
.Parameters.Append .CreateParameter("#OBJ_COMMENTS", adVarChar, adParamInput, 250, "Some text")
.Parameters.Append .CreateParameter("#TIME21_ID", adInteger, adParamInput, 2, 34)
.Parameters.Append .CreateParameter("#WHEREID", adInteger, adParamInput, 18, 456)
.Execute
End With

Data not uploading to MS SQL database.

I'm trying to push a button in an excel worksheet and it should send the data from the a worksheet to the sql table. But this vba code is not uploading the data from excel to the database. I have similar other table and it works fine. Any suggestions or thoughts on this would be great.
Sub Send2SQL()
Dim cmd As New ADODB.Command
Dim rst As ADODB.Recordset
Dim UploadTime, SubmissionNumber, WorkbookSection, DataDescription1, DataDescription2, DataDescription3
Dim iValue, sValue, fValue, bValue, dValue, Omit
Dim UploadRow As Integer
Dim LastRow As Integer
'Establish Error Handler
On Error GoTo ErrorHandler
'Determine UploadTime
UploadTime = Format(Now, "mm\/dd\/yyyy hh\:mm\:ss")
'Loop Through Upload
For UploadRow = 2 To LastRow
With Sheets("DataCapture")
WorkbookSection = .Cells(UploadRow, WorkbookSectionColumn).Value
DataDescription1 = .Cells(UploadRow, DataDescription1Column).Value
DataDescription2 = .Cells(UploadRow, DataDescription2Column).Value
DataDescription3 = .Cells(UploadRow, DataDescription3Column).Value
iValue = .Cells(UploadRow, iValueColumn).Value
sValue = Left(.Cells(UploadRow, sValueColumn).Value, 400)
If sValue = "" Then sValue = Empty
fValue = .Cells(UploadRow, fValueColumn).Value
bValue = .Cells(UploadRow, bValueColumn).Value
dValue = .Cells(UploadRow, dValueColumn).Value
End With
With cmd
.ActiveConnection = conn
.CommandType = adCmdStoredProc
.CommandText = "[DataUpload]"
.Parameters.Append .CreateParameter("#TimeOfUpload", adDBTimeStamp, adParamInput, , UploadTime)
.Parameters.Append .CreateParameter("#WorkbookSection", adVarChar, adParamInput, 60, WorkbookSection)
.Parameters.Append .CreateParameter("#DataDescription1", adVarChar, adParamInput, 255, DataDescription1)
.Parameters.Append .CreateParameter("#DataDescription2", adVarChar, adParamInput, 60, DataDescription2)
.Parameters.Append .CreateParameter("#DataDescription3", adVarChar, adParamInput, 60, DataDescription3)
.Parameters.Append .CreateParameter("#iValue", adBigInt, adParamInput, , iValue)
.Parameters.Append .CreateParameter("#sValue", adVarChar, adParamInput, 400, sValue)
.Parameters.Append .CreateParameter("#fValue", adDouble, adParamInput, , fValue)
.Parameters.Append .CreateParameter("#bValue", adBoolean, adParamInput, , bValue)
.Parameters.Append .CreateParameter("#dValue", adDate, adParamInput, , dValue)
.Parameters.Append .CreateParameter("#FileID", adBigInt, adParamInput, , rstOut)
Set rst = .Execute
End With
Set cmd = New ADODB.Command
Next UploadRow
'Turn off ErrorHandler & Exit Sub
On Error GoTo 0
Exit Sub
ErrorHandler:
MsgBox "There was an Error Uploading your data" & vbNewLine & vbNewLine & "An Automated Email has been sent to Sai Latha Suresh from Acturaial"
On Error GoTo 0
End
End Sub
You are using Execute on your Recordset, when you should be using Execute on your Command object.
From Excel to SQL Server? Try it this way.
Sub Rectangle1_Click()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
My setup looks like this.
Also.......Excel VBA - Update SQL Server Table:
http://www.cnblogs.com/anorthwolf/archive/2012/04/25/2470250.html
http://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm
...More
http://www.ozgrid.com/forum/showthread.php?t=169953
http://stackoverflow.com/questions/2567150/excel-vba-sql-data
http://msgroups.net/microsoft.public.excel.programming/vba-to-export-large-tables/61433
http://www.codeproject.com/Questions/475817/Howplustoplusupdateplussqlplusserverplusdataplusfr
http://www.excelguru.ca/forums/showthread.php?992-SQL-Select-Insert-Update-queries-from-Excel-vba
http://www.mrexcel.com/forum/excel-questions/617303-updating-records-access-table-using-excel-visual-basic-applications.html
http://www.excelforum.com/excel-programming-vba-macros/501147-how-to-use-vba-to-update-a-sql-server-table-from-a-spreadsheet.html

export entire excel sheet to sql table with VBA

having issue sending entire sheet to sql table. I have tried 2 different ways as shown below. both work in different ways. Ultimately I am struggling with exporting multiple rows of data to sql DB
this 1st way I can import multiple rows to sql table successfully with one click of the button, only problem is that the StartTime and FinishTime come to sql table as 00:00:00 even if I enter a normal time in excel
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sEventDate, sID, sDeptCode, sOpCode, sStartTime, sFinishTime, sUnits As String
With Sheets("Sheet1")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=db\db1;Initial Catalog=PTW;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in FirstName
Do Until .Cells(iRowNo, 1) = ""
sEventDate = .Cells(iRowNo, 1)
sID = .Cells(iRowNo, 2)
sDeptCode = .Cells(iRowNo, 3)
sOpCode = .Cells(iRowNo, 4)
sStartTime = .Cells(iRowNo, 5).Text
sFinishTime = .Cells(iRowNo, 6).Text
sUnits = .Cells(iRowNo, 7)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.TimeLog (EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', cast('" & dStartTime & "' as datetime), cast('" & dFinishTime & "' as datetime), '" & sUnits & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Data Successfully Exported."
conn.Close
Set conn = Nothing
End With
End Sub
this 2nd way works and sends the StartTime and FinishTime exactly as it is in excel table, but it only allows me to send one row to sql table at a time
Sub Button1_Click()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim strSQL As String
strSQL = "INSERT INTO dbo.TimeLog" & _
"(EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) " & _
"VALUES (?,?,?,?,?,?,?)"
Set conn = New ADODB.Connection
conn.Open "Provider=SQLOLEDB;Data Source=db\db1;Initial Catalog=PTW;Integrated Security=SSPI;"
iRowNo = 1
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = strSQL
With Sheets("Sheet1")
'Loop until empty cell in FirstName
Do Until .Cells(iRowNo, 1) = ""
cmd.Parameters.Append _
cmd.CreateParameter("pEventDate", adVarChar, adParamInput, 8, .Cells(iRowNo, 1))
cmd.Parameters.Append _
cmd.CreateParameter("pID", adInteger, adParamInput, , .Cells(iRowNo, 2))
cmd.Parameters.Append _
cmd.CreateParameter("pDeptCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 3))
cmd.Parameters.Append _
cmd.CreateParameter("pOpCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 4))
cmd.Parameters.Append _
cmd.CreateParameter("pStartTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 5))
cmd.Parameters.Append _
cmd.CreateParameter("pFinishTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 6))
cmd.Parameters.Append _
cmd.CreateParameter("pUnits", adInteger, adParamInput, , .Cells(iRowNo, 7))
cmd.Execute
iRowNo = iRowNo + 1
Loop
MsgBox "Data Successfully Exported"
End With
conn.Close
Set conn = Nothing
End Sub
you must cast the value. In mssql, yourt time value is recognized as string.
cast('8:00:00' as datetime)
conn.Execute "insert into dbo.TimeLog (EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', cast('" & dStartTime & "' as datetime), cast('" & dFinishTime & "' as datetime), '" & sUnits & "')"
Adding this inside the loop of the first script was the result I was looking for...
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = strSQL

Resources