Loop through range and insert values into SQL Table - vba

A set of data in Excel looking like this:
Test1 12345678 1906 John GY DFS H1C Y
Test2 12345678 1806 Jack GY GQ H1C Y
Test3 12345678 1706 Kate GY GQ H1C Y
Test4 12345678 1606 Sawyer GY GQ H1C
The very last column is to check if data was already loaded to SQL Server.
I have written code to iterate through range and insert values into SQL Table. Within this code, it also checks that last column, if there is a Y, it should skip iteration and go to the next one..
It gives me an error, saying "Else without if".
Sub Connection()
Dim Conn As ADODB.Connection
Dim Command As ADODB.Command
Set Conn = New ADODB.Connection
Set Command = New ADODB.Command
Dim i As Integer
Dim rownumber As Integer
rownumber = Sheets("Sheet1").Range("A1048576").End(xlUp).Row
Conn.ConnectionString = "Provider=SQLOLEDB; Data Source=[Server];Initial Catalog=[DB];User ID=[user];Password=[Password]; Trusted_Connection=no"
Conn.Open
Command.ActiveConnection = Conn
For i = 1 To rownumber 'rows
If ActiveSheet.Cells(i, 8).Value = "Y" Then GoTo NextIteration
Else
Command.CommandText = "INSERT INTO [Database] (" & _
"[Col1], [Col2], [Col3], [Col4], [Col5], [Col6], [Col7])" & _
"VALUES (" & _
"'" & ActiveSheet.Cells(i, 1).Value & "'," & _
"'" & ActiveSheet.Cells(i, 2).Value & "'," & _
"'" & ActiveSheet.Cells(i, 3).Value & "'," & _
"'" & ActiveSheet.Cells(i, 4).Value & "'," & _
"'" & ActiveSheet.Cells(i, 5).Value & "'," & _
"'" & ActiveSheet.Cells(i, 6).Value & "'," & _
"'" & ActiveSheet.Cells(i, 7).Value & "')"
Command.Execute
ActiveSheet.Cells(i, 8).Value = "Y"
End If
Next i
Conn.Close
Set Conn = Nothing
End Sub
I am really struggling to figure out where I went wrong. The code works perfectly fine without checking if "Y" is there...
I appreciate your help.

Try the following
Use Option Explicit at the top to check for variable declarations
Use Long not Integer to avoid potential overflow as you are working with numbers of rows which can exceed capacity of Integer
If statement needs to be broken over several lines to function with Else
Your GoTo referenced a label, NextIteration, which needed adding, You need to verify this is now in the correct place.
Avoid calling your sub connection and use something less ambiguous for the compiler
Public Sub My_Connection()
Dim Conn As ADODB.Connection
Dim Command As ADODB.Command
Set Conn = New ADODB.Connection
Set Command = New ADODB.Command
Dim i As Long
Dim rownumber As Long
rownumber = Worksheets("Sheet1").Range("A1048576").End(xlUp).Row
Conn.ConnectionString = "Provider=SQLOLEDB; Data Source=[Server];Initial Catalog=[DB];User ID=[user];Password=[Password]; Trusted_Connection=no"
Conn.Open
Command.ActiveConnection = Conn
For i = 1 To rownumber 'rows
If ActiveSheet.Cells(i, 8).Value = "Y" Then
GoTo NextIteration
Else
Command.CommandText = "INSERT INTO [Database] (" & _
"[Col1], [Col2], [Col3], [Col4], [Col5], [Col6], [Col7])" & _
"VALUES (" & _
"'" & ActiveSheet.Cells(i, 1).Value & "'," & _
"'" & ActiveSheet.Cells(i, 2).Value & "'," & _
"'" & ActiveSheet.Cells(i, 3).Value & "'," & _
"'" & ActiveSheet.Cells(i, 4).Value & "'," & _
"'" & ActiveSheet.Cells(i, 5).Value & "'," & _
"'" & ActiveSheet.Cells(i, 6).Value & "'," & _
"'" & ActiveSheet.Cells(i, 7).Value & "')"
Command.Execute
ActiveSheet.Cells(i, 8).Value = "Y"
End If
NextIteration:
Next i
Conn.Close
Set Conn = Nothing
End Sub

Add a new line after 'Then' on the first if statement or elses vba implicity closes the if statement.

Related

Slow running Loop. Looking to find way to execute multiple records per execute

I have an excel workbook that contains about 5,000 rows of data. I have two buttons mapped to macros. One button will delete all data in the table, and reinsert it from the Excel Workbook, and the other will only insert the 'new' rows based on a unique ID.
I am finding that both of these buttons are taking a long time to run. ~10-15 minutes. Right now, it is performing the insert for every row, but I am looking to combine this.
Basically, I would like to loop through ~100 or so rows then insert. Then loop through the next hundred rows and insert.
Any suggestions would be greatly appreciated. VBA / Coding in general is not my forte and i'm pulling a brick wall on this one.
Thanks!
Sub Rebuild_Click()
' ***********************
' ** Declare Variables **
' ***********************
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sSTATUS, sCHANNEL, sISSUE, sLOB, sDESC, sIN, sJN, sIS, sPRIME, sIU, sTR, sAU As String
Dim answer, sQTY, sRRSC, sOA, sMeetings, sOutages As Integer
Dim sDATE As Date
With Sheets("OASYS ADMIN TRACKER")
' ****************************
' ** Show Information Popup **
' ****************************
answer = MsgBox("You are about to update the database with ~5,000 records." & vbCrLf & "" & vbCrLf & "This will take approximately 5 minutes." & vbCrLf & "" & vbCrLf & "If you wish to continue, please press Yes. Otherwise, Press No" & vbCrLf & "" & vbCrLf & "----------" & vbCrLf & "EXCEL IS NOT FROZEN." & vbCrLf & "" & vbCrLf & "****DO NOT CLOSE EXCEL ****", vbYesNo + vbQuestion, "Update Database")
' ***********************
' ** Open IF Statement **
' ***********************
If answer = vbYes Then
' ***********************
' ** Connection String **
' ***********************
conn.Open "Provider=SQLNCLI11;Password=XXXXX;User ID=XXXXX;Initial Catalog=SupportAdmin;Data Source=tcp:XXXXX;"
' *************************
' ** Purge Existing Data **
' *************************
conn.Execute "Delete FROM dbo.TestDB"
' *********************
' ** Skip Leader Row **
' *********************
iRowNo = 4
' ************************
' ** Begin Dataset Loop **
' ************************
Do Until .Cells(iRowNo, 3) = ""
sID = .Cells(iRowNo, 1)
sSTATUS = .Cells(iRowNo, 2)
sDATE = .Cells(iRowNo, 3)
sCHANNEL = .Cells(iRowNo, 4)
sISSUE = .Cells(iRowNo, 5)
sQTY = .Cells(iRowNo, 6)
sLOB = .Cells(iRowNo, 7)
sDESC = .Cells(iRowNo, 8)
sIN = .Cells(iRowNo, 9)
sJN = .Cells(iRowNo, 10)
sIS = .Cells(iRowNo, 11)
sPRIME = .Cells(iRowNo, 12)
sIU = .Cells(iRowNo, 13)
sTR = .Cells(iRowNo, 14)
sAU = .Cells(iRowNo, 15)
sRRSC = .Cells(iRowNo, 16)
sOA = .Cells(iRowNo, 17)
sOutages = .Cells(iRowNo, 18)
sMeetings = .Cells(iRowNo, 19)
' ***********************
' ** Replace ' in Data **
' ***********************
sDESC = Replace(sDESC, "'", "''")
sIS = Replace(sIS, "'", "''")
sIU = Replace(sIU, "'", "''")
' *****************
' ** Execute SQL **
' *****************
conn.Execute "insert into dbo.TestDB (ID,STATUS,DATE,CHANNEL,ISSUE,QTY,LOB,[DESC],[IN],JN,[IS],PRIME,IU,TR,AU,RRSC,OA,OUTAGES,MEETINGS) " & _
"values ('" & sID & "','" & sSTATUS & "', '" & sDATE & "','" & sCHANNEL & "', '" & sISSUE & "', '" & sQTY & "', '" & sLOB & "', '" & sDESC & "', '" & sIN & "', '" & sJN & "', '" & sIS & "', '" & sPRIME & "', '" & sIU & "', '" & sTR & "', '" & sAU & "', '" & sRRSC & "', '" & sOA & "', '" & sOutages & "', '" & sMeetings & "')"
iRowNo = iRowNo + 1
Loop
' ****************************
' ** Show Information Popup **
' ****************************
MsgBox "Database Update Complete!"
' *****************************
' ** Close Connection String **
' *****************************
conn.Close
Set conn = Nothing
' ****************************
' ** Close IF Statement **
' ****************************
Else
' do nothing
End If
End With
End Sub
Tried your code with makeshift table in local SQL Server 2005 and found taking only 10 seconds for around 5000 records. In your case the delay may be due to Database Size, network speed etc.
However after trying it with code to insert 100 records at a time the same time reduced to 1 odd second only.
Sub test2()
Dim conn As New ADODB.Connection
Dim LastRow As Long, LastCol As Long, iRowNo As Long, DataArr As Variant
Dim SqStr As String, ValStr As String, Rw As Long, Cl As Long
Dim Ws As Worksheet, tm As Double
tm = Timer
conn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;;Initial Catalog=test;Data Source=USER-PC\SQLEXPRESS"
conn.Execute "Delete FROM dbo.Test"
Set Ws = ThisWorkbook.Worksheets("Sheet1")
iRowNo = 4
LastRow = Ws.Range("C" & Rows.Count).End(xlUp).Row
DataArr = Ws.Range("A" & iRowNo & ":S" & LastRow)
LastCol = UBound(DataArr, 2)
SqStr = "insert into dbo.Test (ID,STATUS,DATE,CHANNEL,ISSUE,QTY,LOB,[DESC],[IN],JN,[IS],PRIME,IU,TR,AU,RRSC,OA,OUTAGES,MEETINGS) "
'Sqlstr=Sqlstr & " Values " 'May use for Sql Server 2008 and above
For Rw = 1 To UBound(DataArr, 1)
DataArr(Rw, 1) = Replace(DataArr(Rw, 1), "'", "''")
DataArr(Rw, 8) = Replace(DataArr(Rw, 8), "'", "''")
DataArr(Rw, 13) = Replace(DataArr(Rw, 13), "'", "''")
'ValStr = ValStr & "('" 'May use for Sql Server 2008 and above
ValStr = ValStr & "Select '"
For Cl = 1 To UBound(DataArr, 2)
'ValStr = ValStr & DataArr(Rw, Cl) & IIf(Cl < LastCol, "','", "')") 'May use for Sql Server 2008 and above
ValStr = ValStr & DataArr(Rw, Cl) & IIf(Cl < LastCol, "','", "'") ' Used for test in Sql Server 2005
Next Cl
If Rw Mod 100 = 0 Then ' exceute at 100 records
ValStr = SqStr & ValStr
conn.Execute ValStr
DoEvents
ValStr = ""
Debug.Print Rw, Timer - tm
Else
If Rw < UBound(DataArr, 1) Then
'ValStr = ValStr & ", " 'Modify Comma / Space between datasets of two rows according Sql version Syntax
ValStr = ValStr & " UNION ALL " 'Used for test with Sql Server 2005.
End If
End If
Next Rw
If Rw Mod 100 > 0 Then
ValStr = SqStr & ValStr
conn.Execute ValStr
DoEvents
ValStr = ""
Debug.Print Rw, Timer - tm
End If
Debug.Print "Total Seconds Taken: " & Timer - tm
End Sub
The INSERT SQl syntax along with connection string etc may please be modified for the type & version used by you along with suggestion in #Raymond Nijland's comment.

Excel and MS Access: Method 'open' of object '_Recordset' failed

I am writing this code in Excel to insert into an access database.
INSERT INTO `C:\Users\ABCBASDkJAJDSKk\Desktop\asdgahsdguu.accdb`.`Table1` Values ('ABCD', 'ABCD','ABCD,ABCD','NA','Success','Several of the above','NA','NA','NA','NA','NA','NA','NA','AB',12)
I am getting the error Method open of object Recordset failed at the rs.open statement.
Any thoughts on why this is happening?
Below is the code
Sub merge_update()
Dim ws As Worksheet
Set ws = Sheets("Darwin Merge Set")
lastrow = ws.Range("B" & Rows.count).End(xlUp).Row
Dim cmd1 As ADODB.Command
Application.ScreenUpdating = False
Dim i As Integer
Dim cn As ADODB.Connection
Set cn = New Connection
strFile = "C:\Users\ABCBASDkJAJDSKk\Desktop\asdgahsdguu.accdb"
cn.Provider = " Provider=Microsoft.ACE.OLEDB.15.0 "
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" & strFile & ";Persist Security Info=false;"
Dim rs As New ADODB.Recordset
cn.Open
For i = 7 To lastrow
src = Range("b" & i).Value
tar = Range("c" & i).Value
dmc = Range("d" & i).Value
gl = Range("e" & i).Value
mo = Range("f" & i).Value
msa = Range("g" & i).Value
fm = Range("h" & i).Value
rsnm = Range("i" & i).Value
em = Range("j" & i).Value
sa = Range("k" & i).Value
rbsc = Range("l" & i).Value
qao = Range("m" & i).Value
qac = Range("n" & i).Value
lo = Range("o" & i).Value
mpl = Range("p" & i).Value
mon = Range("q" & i).Value
stmt = "INSERT INTO `" & strFile & "`.`Table1`"
stmt = stmt & " Values ('" & src & "', '" & tar & "','" & dmc & "','" & gl & "','" & mo & "','" & msa & "','" & fm & "','" & rsnm & "','" & em & "','" & sa & "','" & rbsc & "','" & qao & "','" & qac & "','" & mpl & "'," & mon & ") "
cmd1.ActiveConnection = cn
cmd1.CommandText = stmt
Set rs = cmd1.Execute
Next i
cn.Close
End Sub
You aren't using a command object, you want to replace the RecordSet with a Command. The recordset is where the values come back from the database.
here is a link with a lot of good examples for you.
http://support.microsoft.com/kb/168336/en-us
One example (the New in the Dim cmd1 line is important.
Dim cmd1 As New ADODB.Command
' Recordset Open Method #2: Open via Command.Execute(...)
Conn1.ConnectionString = AccessConnect
Conn1.Open
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "SELECT * FROM Employees"
Set Rs1 = Cmd1.Execute
Rs1.Close
Conn1.Close
Conn1.ConnectionString = ""

VBScript to import specific column of SQL Server database to excel

I am developing a vbscript in which i need to import some values from particular column of specific table of SQL Server DB to MS Excel. I dont have any clue about this.
Could you please suggest me the way in which i can achieve the above scenario.
Option Explicit
Const adOpenStatic = 3
Const adLockOptimistic = 3
dim strSqlInsertString,objConnection1,objConnection2,objRecordSet1,objRecordSet2,strSqlInsertString2
dim objExcel,objWorkBook,objWorkbook1,intRow
Set objConnection1 = CreateObject("ADODB.Connection")
Set objRecordSet1 = CreateObject("ADODB.Recordset")
Set objConnection2 = CreateObject("ADODB.Connection")
Set objRecordSet2 = CreateObject("ADODB.Recordset")
objConnection1.Open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=appapollo;Password=dna;Initial Catalog=6057;Data Source=lxi282"
objConnection2.Open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=appapollo;Password=dna;Initial Catalog=6057;Data Source=lxi282"
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open("D:\Cardiopacs\Automation\Forward\test.xls")
Set objWorkbook = objExcel.ActiveWorkbook.Worksheets(1)
Set objWorkbook1 = objExcel.ActiveWorkbook.Worksheets(2)
intRow = 2
Dim AEName,AEDescription,AEIPAddress,AEPort,ModifiedDate,QRSSApplicationEntityID,MobileAE,NotificationXML,PreFetch,PreFetchSuffix
Dim Enabled,SSDICOMApplicationEntityID,SSDICOMAERoleDescriptionID,AEFunction
Do Until objWorkbook.Cells(intRow,1).Value = ""
'SSDIOMApplicationEntityID = objExcel.Cells(intRow, 1).Value
AEName = objWorkbook.Cells(intRow, 1).Value
AEDescription = objWorkbook.Cells(intRow, 2).Value
AEIPAddress = objWorkbook.Cells(intRow, 3).Value
AEPort = objWorkbook.Cells(intRow, 4).Value
ModifiedDate = objWorkbook.Cells(intRow, 5).Value
QRSSApplicationEntityID = objWorkbook.Cells(intRow, 6).Value
MobileAE = objWorkbook.Cells(intRow, 7).Value
NotificationXML = objWorkbook.Cells(intRow, 8).Value
PreFetch = objWorkbook.Cells(intRow, 9).Value
PreFetchSuffix = objWorkbook.Cells(intRow, 10).Value
strSqlInsertString = "INSERT INTO SSDICOMApplicationEntities (AEName,AEDescription,AEIPAddress,AEPort,ModifiedDate,QRSSApplicationEntityID,MobileAE," & _
"NotificationXML,PreFetch,PreFetchSuffix) " & _
"VALUES('" & AEName & "','" & AEDescription & "','" & AEIPAddress & "','" & AEPort & "','" & ModifiedDate & "','" & QRSSApplicationEntityID & "','" & MobileAE & "'," & _
"'" & NotificationXML & "','" & PreFetch & "','" & PreFetchSuffix & "')"
intRow = intRow + 1
set objRecordSet1=objConnection1.execute(strSQLInsertString)
loop
WScript.Sleep 1000
intRow = 2
Do Until objWorkbook1.Cells(intRow,1).Value = ""
Enabled = objWorkbook1.Cells(intRow, 1).Value
SSDICOMApplicationEntityID = objWorkbook1.Cells(intRow, 2).Value
SSDICOMAERoleDescriptionID = objWorkbook1.Cells(intRow, 3).Value
AEFunction = objWorkbook1.Cells(intRow, 4).Value
strSqlInsertString2 = "INSERT INTO SSDICOMAERoles (Enabled,SSDICOMApplicationEntityID,SSDICOMAERoleDescriptionID,AEFunction)" & _
"VALUES('" & Enabled & "','" & SSDICOMApplicationEntityID & "','" & SSDICOMAERoleDescriptionID & "','" & AEFunction & "')"
intRow = intRow + 1
set objRecordSet1=objConnection1.execute(strSQLInsertString2)
loop
objConnection1.close
set objConnection1 = Nothing
objExcel.Quit
In above code i want to retrieve value of SSDICOMApplicationEntityID from DATABASE and want to put in Excel. Currently i am manually inserting it in Excel.
This is a simple example of moving data the other way using VBA you'll need to do some conversion but I'm guessing not too much:
Option Explicit
Global Const strC As String = _
"PROVIDER=SQLOLEDB.1;" & _
"P******D=**********;" & _
"PERSIST SECURITY INFO=True;" & _
"USER ID=**********;" & _
"INITIAL CATALOG=**********;" & _
"DATA SOURCE=******;" & _
"USE PROCEDURE FOR PREPARE=1;" & _
"AUTO TRANSLATE=True;" & _
"CONNECT TIMEOUT=0;" & _
"COMMAND TIMEMOUT=0" & _
"PACKET SIZE=4096;" & _
"USE ENCRYPTION FOR DATA=False;" & _
"TAG WITH COLUMN COLLATION WHEN POSSIBLE=False"
Sub Import_Using_ADO()
Dim rs As Object
Dim cn As Object
'=====================
'get in touch with the server
Set cn = CreateObject("ADODB.Connection")
cn.Open strC
cn.CommandTimeout = 0
Set rs = CreateObject("ADODB.Recordset")
Set rs.ActiveConnection = cn
With rs
'Extract and copy the required records
.Open "SELECT myColName" & _
" FROM Wdatabase.dbo.myTableName"
With Excel.ThisWorkbook.Sheets(mySheetName)
.Cells(.Rows.Count, 1).End(Excel.xlUp)(2, 1).CopyFromRecordset rs
End With
.Close 'close connection
End With
'=====================
'tidy up
On Error Resume Next
cn.Close
Set cn = Nothing
Set rs = Nothing
Set rs.ActiveConnection = Nothing
'=====================
End Sub

VB the microsoft access database engine could not find the object

I'm receiving the following run time error on VB (Excel 10) "the microsoft access database engine could not find the object". The "Database" is a defined named within a worksheet but it wont pick it up. Any ideas would be hugely appreciated!!
Sub ConnectDB()
If cnn.State <> adStateOpen Then
Dim strFileName As String
strFileName = "O:Children's Fund\APS 2014-15\Refrerral - Allocation Database.xlsx"
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strFileName & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
End If
End Sub
Sub CopyData()
ConnectDB
Dim rst As New ADODB.Recordset
Dim CurrentID As Long
Dim vbResult As VbMsgBoxResult
rst.Open "SELECT * FROM [A2:M1000];", cnn, adOpenStatic, adLockReadOnly
If Not rst.EOF Then
rst.MoveLast
CurrentID = rst("RefNumber")
CurrentID = CurrentID + 1
Else
CurrentID = 1
End If
Dim sql As String
sql = "Insert into [Database] (refnumber, surname, FirstName, DOB, ReferrerEmail, PreferredSetting, MotherEmployment, FatherEmployment, OtherEmployment, Other1Employment, Attendance, Exclusions) values ('" & _
CurrentID & "','" & [FormSurname] & "','" & [FormFirstName] & "','" & [FormDOB] & "','" & [FormEmail] & "','" & [FormPreferred] & "','" & [FormMother] & "','" & [FormFather] & "','" & [FormOther] & "','" & [FormOther1] & "','" & [FormAttendance] & "','" & [FormExclusions] & "')"
cnn.Execute (sql)
MsgBox "Record Saved to Database"
DisconnectDB
End Sub
Sub DisconnectDB()
If cnn.State <> adStateClosed Then
cnn.Close
Set cnn = Nothing
End If
End Sub
Many Thanks
Sam

How to export spreadsheet data into SQLServer?

I am new to Vba, hope someone will solve my problem. I am trying to update data present in my spreadsheet. Actually i have 20,000 records, each record has around 74 columns. So updating them record by record by using ADO taking so much of time. Is there any alternative approach to update those records in single shot. Any help would be appreciated greatly.
Currently my code is.
Sub InitialExport()
On Error GoTo ErrHandler
Dim con As New ADODB.Connection
Dim Query As String
Dim EffectedRecs As Long
Dim i As Integer
ServerName = "192.178.78.36"
'Setting ConnectionString
con.ConnectionString = "Provider=SQLOLEDB; " & _
"Data Source=" & ServerName & "; " & _
"Initial Catalog=AppEmp;" & _
"User ID=sa; Password=admin08; "
'Setting provider Name
con.Provider = "Microsoft.JET.OLEDB.12.0"
'Opening connection
con.Open
With ThisWorkbook.Sheets("Export")
For i = 3 To ThisWorkbook.Sheets("Export").Range("B65536").End(xlUp).Row
'---------------------->
EmpId = .Range("B" & i).Value 'Emp Code-varchar
C = .Range("C" & i).Value 'Emp Name-varchar
D = .Range("D" & i).Value
E = .Range("E" & i).Value
F = .Range("F" & i).Value
G = .Range("G" & i).Value
H = .Range("H" & i).Value
II = .Range("I" & i).Value
JJ = .Range("J" & i).Value
k = .Range("K" & i).Value
l = .Range("L" & i).Value
M = .Range("M" & i).Value
N = CheckNull(.Range("N" & i).Value)
O = CheckNull(.Range("O" & i).Value)
P = CheckNull(.Range("P" & i).Value)
Q = CheckNull(.Range("Q" & i).Value)
R = CheckNull(.Range("R" & i).Value)
S = .Range("S" & i).Value
T = .Range("T" & i).Value
U = .Range("U" & i).Value
v = .Range("V" & i).Value
W = .Range("W" & i).Value
X = CheckNull(.Range("X" & i).Value)
Y = .Range("Y" & i).Value
Z = .Range("Z" & i).Value
AA = CheckNull(.Range("AA" & i).Value)
AB = .Range("AB" & i).Value
AC = CheckNull(.Range("AC" & i).Value)
AD = CheckNull(.Range("AD" & i).Value)
AE = CheckNull(.Range("AE" & i).Value)
AF = CheckNull(.Range("AF" & i).Value)
AG = .Range("AG" & i).Value
AH = CheckNull(.Range("AH" & i).Value)
AI = CheckNull(.Range("AI" & i).Value)
AJ = CheckNull(.Range("AJ" & i).Value)
AK = CheckNull(.Range("AK" & i).Value)
AL = CheckNull(.Range("AL" & i).Value)
AM = CheckNull(.Range("AM" & i).Value)
AN = CheckNull(.Range("AN" & i).Value)
AO = CheckNull(.Range("AO" & i).Value)
AP = CheckNull(.Range("AP" & i).Value)
AQ = CheckNull(.Range("AQ" & i).Value)
AR = CheckNull(.Range("AR" & i).Value)
aAS = CheckNull(.Range("AS" & i).Value)
AT = .Range("AT" & i).Value
AU = CheckNull(.Range("AU" & i).Value)
AV = CheckNull(.Range("AV" & i).Value)
AW = CheckNull(.Range("AW" & i).Value)
AX = CheckNull(.Range("AX" & i).Value)
AY = CheckNull(.Range("AY" & i).Value)
AZ = CheckNull(.Range("AZ" & i).Value)
BA = CheckNull(.Range("BA" & i).Value)
BB = CheckNull(.Range("BB" & i).Value)
BC = CheckNull(.Range("BC" & i).Value)
BD = CheckNull(.Range("BD" & i).Value)
BE = .Range("BE" & i).Value
BF = .Range("BF" & i).Value
BG = CheckNull(.Range("BG" & i).Value)
BH = .Range("BH" & i).Value
BI = .Range("BI" & i).Value
BJ = CheckNull(.Range("BJ" & i).Value)
BK = CheckNull(.Range("BK" & i).Value)
BL = CheckNull(.Range("BL" & i).Value)
BM = .Range("BM" & i).Value
BN = .Range("BN" & i).Value
Query = "Exec HRApp_P_AddEmpData '" & EmpId & "','" & C & "','" & D & "','" & E & "','" & F & "','" & G & "','" & H & "','" & II & "','" & JJ & "','" & k & "','" & l & "','" & M & "'," & N & "," & O & "," & P & "," & Q & "," & R & ",'" & S & "','" & T & "','" & U & "','" & v & "','" & W & "'," & X & ",'" & Y & "','" & Z & "'," & AA & ",'" & AB & "'," & AC & "," & AD & "," & AE & "," & AF & ",'" & AG & "'," & AH & "," & AI & "," & AJ & "," & AK & ",'" & AL & "'," & AM & "," & AN & "," & AO & "," & AP & "," & AQ & "," & AR & "," & aAS & ",'" & AT & "'," & AU & "," & AV & "," & AW & "," & AX & "," & AY & "," & AZ & "," & BA & "," & BB & "," & BC & "," & BD & ",'" & BE & "','" & BF & "'," & BG & ",'" & BH & "','" & BI & "'," & BJ & "," & BK & "," & BL & ",'" & BM & "','" & BN & "'"
con.Execute Query
Next
End With
con.Close
Set con = Nothing
Exit Sub
ErrHandler: 'MsgBox "The Not able ta Save Data"
Set con = Nothing
End Sub
The above code is working fine. But it is taking more time to update data.:-(
Now my code became like this
Private Sub Worksheet_Activate()
Dim adoConn As New ADODB.Connection
Dim adoRS As New ADODB.Recordset
Dim sQuery As String
Dim EffectedRecs As Long
Dim sFields As String
Dim sValues As String
Dim iRow As Integer
Dim iField As Integer
ServerName = "193.128.125.14"
con_Str = "Provider=SQLOLEDB; " & _
"Data Source=" & ServerName & "; " & _
"Initial Catalog=DB_At&T;" & _
"User ID=sa; Password=ad28; "
sQuery = "select * from Currency where 1=2"
sValues = ""
With adoConn
.ConnectionString = con_Str
.Provider = "Microsoft.JET.OLEDB.12.0"
.CursorLocation = adUseClient
.Open
End With
With adoRS
.ActiveConnection = adoConn
.CursorLocation = adUseClient
.LockType = adLockBatchOptimistic
.CursorType = adOpenKeyset ' adOpenDynamic
.Source = sQuery
.Open
End With
With ThisWorkbook.Sheets("Export")
For iRow = 3 To ThisWorkbook.Sheets("Export").Range("B65536").End(xlUp).Row
For iField = 0 To adoRS.Fields.Count - 1
sFields = sFields & "," & adoRS.Fields(iField).Name
Next
sValues = sValues & "," & .Range("A" & iRow).Value
sValues = sValues & "," & .Range("B" & iRow).Value
sValues = sValues & "," & .Range("C" & iRow).Value
sValues = sValues & "," & .Range("D" & iRow).Value
sFields = Right(sFields, Len(sFields) - 1) 'Removing ,
sValues = Right(sValues, Len(sValues) - 1) 'Removing ,
adoRS.AddNew FieldList = sFields, Values:=sValues
Next
End With
adoRS.UpdateBatch adAffectAllChapters
adoRS.Close
adoConn.Close
End Sub
you could try this:
Sub InitialExport()
On Error GoTo ErrHandler
'
Dim adoConn As New ADODB.Connection
Dim adoRS As ADODB.Recordset
'
Dim sQuery As String
Dim EffectedRecs As Long
Dim sFields As String
Dim sValues As String
'
Dim iRow As Integer
Dim iField As Integer
'
ServerName = SERVER_NAME
'
sQuery="SELECT * from tableName where 1 =2" ' get an empty recordset!
'
'Set the connection and open
with adoConn
.ConnectionString = CONNECTION_STRING
.Provider = "Microsoft.JET.OLEDB.12.0"
.cursorlocation=aduseclient
.Open
end with
'
' set the Recordset and open
With adoRS
.activeconnection=adoconn
.CursorLocation = adUseClient
.LockType = adLockBatchOptimistic
.CursorType = adopenkeyset ' adOpenDynamic
.Source = sQuery
.Open
End With
'
' now get the data into the recordset
With ThisWorkbook.Sheets("Export")
For iRow = 3 To ThisWorkbook.Sheets("Export").Range("B65536").End(xlUp).Row
' here loop through all the columns
For iField = 0 To adoRS.Fields.Count - 1
' adding the column names to the Variable sFields
sFields = sFields & "," & adoRS.Fields(iField).Name
'
' adding the values from the worksheet for this row
sValues = sValues & ", " & .Cells(iRow, iField).Text
Next
'
' add a new record with the fields and values
adoRS.AddNew FieldList:=sFields, Values:=sValues
'
Next
'
' update all the rows in one step
adoRS.UpdateBatch adAffectAllChapters ' update them all in one step!
'
End Sub
just change tablename in the query to the correct table and make sure the columns in the worksheet are in the same order and datatype as the columns in the table
for ADO Recordset help see:
MSDN Library - ADO Recordset, AddNew method
and
MSDN Library - ADO Recordset, UpdateBatch
and
W3Schools
I hope that get's you started!
Philip
Another option could be uploading your entire Excel Sheet as a csv file directly into the server using BulkInsert.
The Sql code might look as simple as this:
BULK INSERT [DB].[dbo].[Importa_Aux] FROM '\\share\filename.csv' WITH ( FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n' , FIRSTROW = 2 )
Then simply work your data updates in SqlServer.