VBScript to import specific column of SQL Server database to excel - sql

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

Related

Updating SQL Table via VBA cuts off decimals

I need to update a set of values from an Excel Worksheet into a SQL Server Table.
This is the Excel Table:
I wrote some code in VBA to do this, but I'm not very expert.
The update work just fine except for the part where it truncate decimals.
As you can see the decimals get cuts off. The fields on SQL are declared as Decimal (19,5).
Sure there's something wrong in the VBA code. Here's my code.
On Error GoTo RigaErrore
Dim cn_ADO As Object
Dim cmd_ADO As Object
Dim SQLUser As String
Dim SQLPassword As String
Dim SQLServer As String
Dim DBName As String
Dim DBConn As String
Dim SQLQuery As String
Dim strWhere As String
Dim i As Integer
Dim jOffset As Integer
Dim iStartRow As Integer
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'iStep = 100
jOffset = 20
iStartRow = 3
i = iStartRow
SQLUser = "xxxx"
SQLPassword = "xxx"
SQLServer = "xxxxxxxx"
DBName = "xxxxx"
DBConn = "Provider=SQLOLEDB.1;Pesist Security Info=True;User ID=" & SQLUser & ";Password=" & SQLPassword & ";Initial Catalog=" & DBName & ";" & _
"Data Source=" & SQLServer & ";DataTypeCompatibility=80;"
Set cn_ADO = CreateObject("ADODB.Connection")
cn_ADO.Open DBConn
Set cmd_ADO = CreateObject("ADODB.Command")
While Cells(i, jOffset).Value <> ""
xlsIDKey = Cells(i, 0 + jOffset)
xlsVendSim = CDbl(Cells(i, 1 + jOffset))
xlsOreSim = CDbl(Cells(i, 2 + jOffset))
xlsProdVar = CDbl(Cells(i, 3 + jOffset))
xlsOreSimVar = CDbl(Cells(i, 4 + jOffset))
strWhere = "ID_KEY = '" & xlsIDKey & "'"
SQLQuery = "UPDATE DatiSimulati " & _
"SET " & _
"VEND_SIM = Cast(('" & xlsVendSim & "') as decimal (19,5)), " & _
"ORE_SIM = Cast(('" & xlsOreSim & "') as decimal (19,5)), " & _
"PROD_VAR = Cast(('" & xlsProdVar & "') as decimal (19,5)), " & _
"ORE_SIM_VAR = Cast(('" & xlsOreSimVar & "') as decimal (19,5)) " & _
"WHERE " & strWhere
cmd_ADO.CommandText = SQLQuery
cmd_ADO.ActiveConnection = cn_ADO
cmd_ADO.Execute
i = i + 1
Wend
Set cmd_ADO = Nothing
Set cn_ADO = Nothing
Exit Sub
RigaErrore:
MsgBox Err.Number & vbNewLine & Err.Description
Application.StatusBar = False
Application.Cursor = xlDefault
If Not cn_ADO Is Nothing Then
Set cn_ADO = Nothing
End If
If Not cmd_ADO Is Nothing Then
Set cmd_ADO = Nothing
End If
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Thanks everybody who could help solve this.
A work-around would be to replace the decimal commas with dots.
Option Explicit
Sub connectDB()
Const SQLUser = "#"
Const SQLPassword = "#"
Const SQLServer = "#"
Const DBName = "#"
Dim DBConn As String
DBConn = "Provider=SQLOLEDB.1;Pesist Security Info=True" & _
";User ID=" & SQLUser & ";Password=" & SQLPassword & _
";Initial Catalog=" & DBName & _
";Data Source=" & SQLServer & _
";DataTypeCompatibility=80;"
Dim cn_ADO As Object, cmd_ADO As Object
Set cn_ADO = CreateObject("ADODB.Connection")
cn_ADO.Open DBConn
Set cmd_ADO = CreateObject("ADODB.Command")
cmd_ADO.ActiveConnection = cn_ADO
Const joffset = 20
Const iStartRow = 3
Dim SQLQuery As String, sIDKey As String
Dim sVendSim As String, sOreSim As String
Dim sProdVar As String, sOreSimVar As String
Dim i As Long
i = iStartRow
' create log file
Dim LOGFILE As String
LOGFILE = ThisWorkbook.Path & "\logfile.txt"
Dim fs As Object, ts As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.CreateTextFile(LOGFILE, True)
While Len(Cells(i, joffset).Value) > 0
sIDKey = Cells(i, 0 + joffset)
sVendSim = Replace(Cells(i, 1 + joffset), ",", ".")
sOreSim = Replace(Cells(i, 2 + joffset), ",", ".")
sProdVar = Replace(Cells(i, 3 + joffset), ",", ".")
sOreSimVar = Replace(Cells(i, 4 + joffset), ",", ".")
SQLQuery = "UPDATE DatiSimulati " & _
"SET " & _
"VEND_SIM = " & sVendSim & ", " & _
"ORE_SIM = " & sOreSim & ", " & _
"PROD_VAR = " & sProdVar & ", " & _
"ORE_SIM_VAR = " & sOreSimVar & " " & _
"WHERE ID_KEY = " & sIDKey
ts.writeline SQLQuery & vbCr
cmd_ADO.CommandText = SQLQuery
cmd_ADO.Execute
i = i + 1
Wend
ts.Close
MsgBox i - iStartRow & " records updated see " & LOGFILE, vbInformation
End Sub

Format Issue on Excel Query Table

I am trying to pull the data with SQL query in excel. Query working fine and giving exact result but issue is I am passing the date variable 01-02-2005 in query and getting output -2006 (Last Column). I tried many possible ways as of my knowledge , it's doesn't work . please suggest how to get the custom date 01-02-2005 .
refer code
Sub CreateGLTable()
Const adOpenKeyset = 1
Const adLockOptimistic = 3
Const WORKSHEETNAME As String = "Sheet1"
Const TABLENAME As String = "Table1"
Dim conn As Object, rs As Object
Dim tbl As ListObject
Dim Destination As Range
Set Destination = ThisWorkbook.Worksheets("GL_OUTPUT").Range("a1")
Set conversiongl = ThisWorkbook.Worksheets("GL_OUTPUT")
ThisWorkbook.Worksheets("GL_MEMO").Range("E1").NumberFormat = "#"
Set rg = ThisWorkbook.Worksheets("GL_MEMO").UsedRange
Set tbl = ThisWorkbook.Worksheets("GL_MEMO").ListObjects.Add(xlSrcRange, rg, , xlYes)
With tbl.Sort
.SortFields.Clear
.SortFields.Add _
Key:=.Parent.ListColumns("NATURAL_ACCOUNT").DataBodyRange, SortOn:=xlSortOnValues, Order:= _
xlDescending, DataOption:=xlSortNormal
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Set tbl = Worksheets(WORKSHEETNAME).ListObjects(TABLENAME)
Set conn = CreateObject("ADODB.Connection")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
conn.Open
' On Error GoTo CloseConnection
Set rs = CreateObject("ADODB.Recordset")
With rs
.ActiveConnection = conn
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Source = getGLSQL(tbl)
.Open
With Destination
'tbl.HeaderRowRange.Copy .Range("c1")
.Range("a1").CopyFromRecordset rs
.Parent.ListObjects.Add SourceType:=xlSrcRange, Source:=.Range("a1").CurrentRegion, XlListObjectHasHeaders:=xlYes, TableStyleName:=tbl.TableStyle
End With
End With
tbl.Unlist
CloseRecordset:
rs.Close
Set rs = Nothing
CloseConnection:
conn.Close
Set conn = Nothing
conversiongl.Copy
With Workbooks(Workbooks.Count)
.SaveAs Filename:="E:\GL.glm", FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
End Sub
Function getGLSQL(tbl As ListObject) As String
Dim SQL As String, SheetName As String, RangeAddress As String
Dim strcur, strbranch, strSource, StrtimeStampDate As String
strcur = "'INR'"
strbranch = "'CHEN'"
strSource = "'Northern Arc'"
StrtimeStampDate = ThisWorkbook.Worksheets("sheet2").Range("b2").Value
SQL = " SELECT " & strbranch & " as [Branch]" & _
", " & strcur & " as [CURRENCY]" & _
", [NATURAL_ACCOUNT]" & _
", Left([gl_desc_2], 50) as [gl_desc_2]" & _
", IIF(isnull([AMT]), 0, [AMT]) as [AMT1]" & _
", IIF(isnull([AMT]), 0, [AMT]) as [AMT2]" & _
", " & strSource & " as [SOURCE] " & _
", " & StrtimeStampDate & " as [TimeStamp] " & _
" FROM" & _
"( SELECT sum([NET]) * -1 AS [AMT]" & _
", [NATURAL_ACCOUNT] as [NATURAL_ACCOUNT]" & _
", [gl_desc_2]" & _
" FROM [SheetName$RangeAddress] " & _
" group by ([natural_account]), [gl_desc_2] )"
'SQL = "Select [NATURAL_ACCOUNT] FROM [SheetName$RangeAddress] "
SheetName = tbl.Parent.Name
RangeAddress = tbl.Range.Address(False, False)
Debug.Print SheetName
Debug.Print RangeAddress
SQL = Replace(SQL, "SheetName", SheetName)
SQL = Replace(SQL, "RangeAddress", RangeAddress)
getGLSQL = SQL
End Function
Change
StrtimeStampDate = ThisWorkbook.Worksheets("sheet2").Range("b2").Value
To
StrtimeStampDate = "#" & Format(ThisWorkbook.Worksheets("sheet2").Range("b2").Value,"dd mmm yyyy") & "#"

Loop through range and insert values into SQL Table

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.

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 = ""

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.