I have some data in an Excel form and I want to import it into database. I also want to retrieve some data from database. I am using VBA for connecting to database it my code is giving me an error.
Here is the code:
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
'Open a connection to SQL Server
conn.Provider = "sqloledb"
conn.Properties("Prompt") = adPromptAlways
conn.Open "Data Source=localhost;Initial Catalog=bank;"
'conn.Open "Provider=SQLOLEDB;Data Source=ASUSBOOK\SQL2012;Initial Catalog=ExcelDemo;Integrated Security=SSPI;"
Set rs.ActiveConnection = conn
rs.Open "select code from info"
startrow = 2
Do Until rs.EOF
Cells(startrow, 5) = rs.Fields(0).Value
rs.MoveNext
startrow = startrow + 1
Loop
rs.Close
Set rs = Nothing
Dim iRowNo As Integer
Dim accountno, Amount, code As String
Dim Rowcount As Integer
Rowcount = 1
With Sheets("Sheet1")
iRowNo = 2
Do Until .Cells(iRowNo, 1) = ""
accountno = .Cells(iRowNo, 1)
Amount = .Cells(iRowNo, 2)
.Cells(iRowNo, 3) = "OK"
.Cells(iRowNo, 4) = Rowcount
.Cells(iRowNo, 5) = Post_Date
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Provider = "sqloledb"
conn.Properties("Prompt") = adPromptAlways
conn.Open "Data Source=localhost;Initial Catalog=bank;"
conn.Execute "insert into dbo.Customers (AccountNo,Amount,code) values ('" & accountno & "', '" & Amount & "', '" & code & "')"
iRowNo = iRowNo + 1
Rowcount = Rowcount + 1
DoEvents
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
End Sub
Set the CursorLocation property of the ADO Recordset to adUseClient:
conn.CursorLocation = adUseClient
Related
I would like to know how to get a stored procedure as a text and update its twin(!) on the other server with an excel macro. So I got this stored procedure on the server which has the newest version of the stored procedure:
Declare #Lines Table (Line NVARCHAR(MAX));
Declare #FullText NVARCHAR(max) = '';
INSERT #Lines EXEC sp_helptext 'StoredProcName';
Select #FullText = #FullText + Line From #Lines;
Select #FullText
#Fulltext has the complete code of 'StoredProcName'. I would like to get this code, cut the first 6 letters (CREATE), append it with "ALTER" and run it on the target server/database to update its twin(!). I got this excel macro to realize it:
Sub GetStoredProcedure()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd1 As ADODB.Command
Set cmd1 = New ADODB.Command
'Getting data from local
Set cn = New ADODB.Connection
cn.ConnectionString = _
"Provider=SQLOLEDB;" & _
"Data Source=myDataSource;" & _
"Initial Catalog=myDataBase;" & _
"Integrated Security=SSPI;"
cn.Open 'Connection establishment.
cmd1.ActiveConnection = cn
cmd1.CommandType = adCmdStoredProc
cmd1.CommandText = "UpdateStoredProcedure"
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
Parameter = Cells(i, 1).Value
cmd1.Parameters.Refresh
cmd1.Parameters("#sPName").Value = Parameter
Set rs = cmd1.Execute
rs.Open
Debug.Print rs.State
Range("K2").CopyFromRecordset rs
Next i
rs.Close 'Deactivating the recordset.
cn.Close 'Deactivating the connetion.
End Sub
After running this macro I get the Run-time error '3704': Operation is not allowed when the object is closed.
Thanks in advance for your help.
Try
Option Explicit
Sub GetStoredProcedure()
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim cmd1 As ADODB.Command
'Getting data from local
Set cn = New ADODB.Connection
cn.ConnectionString = _
"Provider=SQLOLEDB;" & _
"Data Source=myDataSource;" & _
"Initial Catalog=myDataBase;" & _
"Integrated Security=SSPI;"
cn.Open 'Connection establishment.
Dim sProc As String, sCode As String, n As Long, i As Long
With Range("K:L")
.Font.Name = "Lucida Console"
.Font.Size = 11
.NumberFormat = "#"
.ColumnWidth = 85
End With
Set cmd1 = New ADODB.Command
With cmd1
.ActiveConnection = cn
.CommandType = adCmdText
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
sProc = Cells(i, 1).Value
.CommandText = "EXEC sp_helptext '" & sProc & "';"
Set rs = .Execute
sCode = rs.GetString
sCode = Replace(sCode, vbCrLf & vbCrLf, vbCrLf)
Range("K" & i).Value = sCode
Range("L" & i).Value = Replace(sCode, "CREATE PROCEDURE", "ALTER PROCEDURE")
n = n + 1
Next i
End With
rs.Close 'Deactivating the recordset.
cn.Close 'Deactivating the connetion.
MsgBox n & " procedures", vbInformation
End Sub
I'm using the VBA code below to import data from my Excel table to SQL server. The code is inserting one row at a time and my tables contains thousands of rows.
To improve the speed of the import I want to import 1.000 rows at a time. How can I modify the code to insert 1.000 rows for each excecution?
I am not very skilled within VBA and found the code on this URL: http://tomaslind.net/2013/12/26/export-data-excel-to-sql-server/
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sCustomerId, sFirstName, sLastName As String
With Sheets("Sheet1")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=MSI\SQL2016;Initial Catalog=ExcelDemo;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sCustomerId = .Cells(iRowNo, 1)
sFirstName = .Cells(iRowNo, 2)
sLastName = .Cells(iRowNo, 3)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "insert into dbo.CustomersStage (CustomerId, FirstName, LastName) values ('" & sCustomerId & "', '" & sFirstName & "', '" & sLastName & "')"
iRowNo = iRowNo + 1
Loop
conn.Execute "EXEC dbo.MergeCustomers"
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
End Sub
Great point! Bulk Insert is the fastest option out there. You can use Excel for this, of course, but that's a very, very, very sub-optimal solution. If you just want to get it done quickly, and easily, save the Excel file as a CSV file, and run the code below.
BULK
INSERT listcustomer
FROM 'c:\your_file.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
If Bulk Insert is not an option for you, consider the two solutions below.
Either.
Sub UpdateTable()
Dim cnn As Object
Dim wbkOpen As Workbook
Dim objfl As Variant
Dim rngName As Range
Workbooks.Open "C:\Users\Excel\Desktop\Excel_to_SQL_Server.xls"
Set wbkOpen = ActiveWorkbook
Sheets("Sheet1").Select
Set rngName = Range(Range("A1"), Range("A1").End(xlToLeft).End(xlDown))
rngName.Name = "TempRange"
strFileName = wbkOpen.FullName
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes"";"
nSQL = "INSERT INTO [odbc;Driver={SQL Server};Server=Your_Server_Name;Database=[Northwind].[dbo].[TBL]]"
nJOIN = " SELECT * from [TempRange]"
cnn.Execute nSQL & nJOIN
MsgBox "Uploaded Successfully"
wbkOpen.Close
Set wbkOpen = Nothing
End Sub
Or.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Your_Server_Name;Database=Northwind;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
To improve the speed of the import I want to import 1.000 rows at a time. How can I modify the code to insert 1.000 rows for each excecution?
Lots of ways, but none easy from VBA. Start by just using a transaction, or loading into a temp table. The way you're currently doing it requires the log file to be flushed after each insert, which is probably most of your elapsed time. Something like:
conn.Execute "begin transaction"
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sCustomerId = .Cells(iRowNo, 1)
sFirstName = .Cells(iRowNo, 2)
sLastName = .Cells(iRowNo, 3)
'Generate and execute sql statement to import the excel rows to SQL Server table
'... set parameter values
conn.Execute "insert into dbo.CustomersStage (CustomerId, FirstName, LastName) values (#CustomerId, #FirstName, #LastName)"
iRowNo = iRowNo + 1
Loop
conn.Execute "commit transaction"
I’ve recently got into SQL Server, trying to build some query to return info (in Excel) from our ERP system (JobBoss) database. I was wondering:
Is there a way to update/change values in the SQL Server database from Excel?
For example, I have established a connection (in Excel) to our SQL Server already, and have a query that SELECTs certain values from specific tables to create a report. However, I was wondering if I can simply change the values in Excel then somehow “upload/synchronize” with the database?
If so, what are the options?
Thanks
Going from Excel to SQL Server? You have several options.
Setup looks link this:
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
Also, consider this option.
Sub UpdateTable()
Dim cnn As Object
Dim wbkOpen As Workbook
Dim objfl As Variant
Dim rngName As Range
Workbooks.Open "C:\Users\Excel\Desktop\Excel_to_SQL_Server.xls"
Set wbkOpen = ActiveWorkbook
Sheets("Sheet1").Select
Set rngName = Range(Range("A1"), Range("A1").End(xlToLeft).End(xlDown))
rngName.Name = "TempRange"
strFileName = wbkOpen.FullName
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes"";"
nSQL = "INSERT INTO [odbc;Driver={SQL Server};Server=Excel-PC\SQLEXPRESS;Database=[Northwind].[dbo].[TBL]]"
nJOIN = " SELECT * from [TempRange]"
cnn.Execute nSQL & nJOIN
MsgBox "Uploaded Successfully"
wbkOpen.Close
Set wbkOpen = Nothing
End Sub
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
See the link below for some additional ideas of how to get this done.
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction
I have large data in Excel that I need to upload to SQL Server but I am using Access as a Front End. Number of columns in Excel are around 90 and number of records goes above 700,000
I just answered a question like this about an hour ago.
Sub Button_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
Also, check out these links.
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm
http://tomaslind.net/2013/12/26/export-data-excel-to-sql-server/
I need to insert test-vba.xlsx data into SQL server to the particular database
Sub insertion()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim m, nrows As Integer
Set wkb = Workbooks("test-vba.xlsx").Worksheets("Sheet1").Activate
sConnString = "Provider=SQLOLEDB;Data Source=PRATEEP-PC\SQLEXPRESS;" & _
"Initial Catalog=PPDS_07Dec_V1_Decomposition;" & _
"Integrated Security=SSPI;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
For m = 0 To nrows - 1
Here are a couple ideas.
Sub UpdateTable()
Dim cnn As Object
Dim wbkOpen As Workbook
Dim objfl As Variant
Dim rngName As Range
Workbooks.Open "C:\Users\Excel\Desktop\Excel_to_SQL_Server.xls"
Set wbkOpen = ActiveWorkbook
Sheets("Sheet1").Select
Set rngName = Range(Range("A1"), Range("A1").End(xlToLeft).End(xlDown))
rngName.Name = "TempRange"
strFileName = wbkOpen.FullName
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes"";"
nSQL = "INSERT INTO [odbc;Driver={SQL Server};Server=Server_Name;Database=[Database_Name].[dbo].[TBL]]"
nJOIN = " SELECT * from [TempRange]"
cnn.Execute nSQL & nJOIN
MsgBox "Uploaded Successfully"
wbkOpen.Close
Set wbkOpen = Nothing
End Sub
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Server_Name;Database=Database_Name;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
Here is another idea.
Sub Button_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
Also, check out the links below.
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