I have an Excel workbook with the below code —
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sFirstName, sLastName As String
With Sheets("Sheet1")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;" & _
"Data Source=server1;" & _
"Initial Catalog=table1;" & _
"User ID=user1; Password=pass1"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sFirstName = .Cells(iRowNo, 1)
sLastName = .Cells(iRowNo, 2)
'Generate and execute sql statement
' to import the excel rows to SQL Server table
conn.Execute "Insert into dbo.Customers (FirstName, LastName) " & _
"values ('" & sFirstName & "', '" & sLastName & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
End Sub
This opens up a connection to my database and inputs the values from the stated columns.
The primary key is an incremental key on the database. The problem is it will copy ALL values.
I’d like to add new rows of data into the Excel Sheet and only insert those rows that don’t already exist.
I’ve tried different methods (‘merge’, ‘if exist’, if not exist’, etc.) but I can’t get it right.
The solution has to be through VBA. Setting up a link using SSMS is not an option.
I understand that it may be possible to use temporary tables and then trigger a procedure which performs the merge but I want to look into that as a last resort. Haven’t read up on it yet (making my way through my MS SQL bible book) but I’m hoping it won’t be necessary.
—Update from @Kannan’s answer—
New portion of VBA —
conn.Execute "IF EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
"THEN UPDATE dbo.customers SET WHERE Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' " & _
"ELSE INSERT INTO dbo.Customers (FirstName, LastName) " & _
"VALUES ('" & sFirstName & "', '" & sLastName & "')"
This returns error ‘Incorrect syntax near the keyword ‘THEN’.
Добрый день!
У меня такой вопрос.
Мне нужно из хранимой процедуры одного сервера SQL записать данные в таблицу на другой сервер SQL.
Я попробовал
Sub Test()
Dim conn As String
Dim data_base As String
Dim period As String
Dim datasource As String
Dim object_id As String
Dim dt As Integer
Dim day_start As String
Dim date_beg As String
Dim date_end As String
conn = «Provider=SQLOLEDB.1;Password=Knpz_asrmb;Persist Security Info=True;User ID=USER_ASRMB;Initial Catalog=TCD_Work;Data Source=Sam-knpz-app24»
conn1 = «Provider=SQLOLEDB.1;Password=ASRMB;Persist Security Info=True;User ID=ASRMB;Initial Catalog=dbm_asrmb_knpz_20190129;Data Source=KNPZ-ASRMB-N1MSSQLASRMB1»
JS_params = «{» + Chr(34) + «id_object» + Chr(34) + «:» + Chr(34) + object_id + Chr(34) + «,» _
+ Chr(34) + «period» + Chr(34) + «:» + Chr(34) + period + Chr(34) + «,» _
+ Chr(34) + «datasource» + Chr(34) + «:» + Chr(34) + CStr(dt) + Chr(34) + «,» _
+ Chr(34) + «date» + Chr(34) + «:» + Chr(34) + day_start + Chr(34) + «,» _
+ Chr(34) + «date_beg» + Chr(34) + «:» + Chr(34) + date_beg + Chr(34) + «,» _
+ Chr(34) + «date_end» + Chr(34) + «:» + Chr(34) + date_end + Chr(34) + «}»
Query conn, JS_params
End Sub
Sub Query(connStr As String, jsonParams As String)
Dim cnDB As New ADODB.Connection
Dim rc As New ADODB.Recordset
cnDB.CommandTimeout = 360
cnDB.Open connStr
Dim params As Object
Set params = JsonConverter.ParseJson(jsonParams)
Dim period As String
Dim object_id As String
Dim day_start As String
Dim date_beg As String
Dim date_end As String
Dim data_source As String
Dim dataseg As String
Dim day1 As String
Dim month1 As String
Dim year1 As String
Dim dt As String
dataseg = Date
ThisWorkbook.Sheets(2).Cells(1, 2).Value = dataseg
day1 = Day(dataseg)
month1 = Mid(dataseg, 4, 2)
year1 = year(dataseg)
ThisWorkbook.Sheets(2).Cells(2, 1).Value = day1
ThisWorkbook.Sheets(2).Cells(3, 1).Value = month1
ThisWorkbook.Sheets(2).Cells(4, 1).Value = year1
dt = year1 + month1 + day1
ThisWorkbook.Sheets(2).Cells(5, 1).Value = dt
period = params(«period»
object_id = params(«id_object»
data_source = params(«datasource»
date_beg = params(«date_beg»
date_end = params(«date_end»
day_start = params(«date»
Dim ws As Worksheet
‘Set ws = Sheets(«Áàëàíñ ïî çàâîäó»
‘ws.UsedRange.Clear
Dim sql As String
sql = «set nocount on EXEC spTCD__KNPZ_shipment ‘» + dt + «‘,1»
rc.Open sql, cnDB
ThisWorkbook.Sheets(1).Cells(1, 1).CopyFromRecordset rc
rc.Close
cnDB.Close
Dim cn1DB As New ADODB.Connection
Dim rc1 As New ADODB.Recordset
cn1DB.CommandTimeout = 360
cn1DB.Open «Provider=SQLOLEDB.1;Password=ASRMB;Persist Security Info=True;User ID=ASRMB;Initial Catalog=dbm_asrmb_knpz_20190129;Data Source=KNPZ-ASRMB-N1MSSQLASRMB1»
Dim sql2 As String
sql2 = «Insert INTO [dbm_asrmb_knpz_20190129].[dbo].[tsd] (id_prod, prod_name, prod_okp,prod_ksm, id_transType, transtype, id_owner, owner, m_netto, shipDT) From rsADO»
rc1.Open sql2, cn1DB
ThisWorkbook.Sheets(3).Cells(1, 1).CopyFromRecordset rc1
rc1.Close
cn1DB.Close
В один рекордсет я записал данные. Но не могу записать из него в таблицу
Hi ,
I am new to excel vba and i have absolutely no idea of how to achieve this.
i want to insert and update a sql server table using excel macro.
currently i have done it for the update can someone please help me in adding the insertion code.
here is the update code below:-
‘General variables we’ll need
Public con As ADODB.Connection
Public bIgnoreChange As Boolean
Dim pk As New Collection
Dim oldValue As Variant
Dim nRecordCount As Integer
Private Sub Workbook_Deactivate()
If Not (con Is Nothing) Then
con.Close
Set con = Nothing
End If
End Sub
Function IsInPrimaryKey(name As String)
For Each pki In pk
If (pki = name) Then
IsInPrimaryKey = True
Exit Function
End If
Next pki
IsInPrimaryKey = False
End Function
Function MakeSQLText(data As Variant)
If (IsNumeric(data)) Then
MakeSQLText = data
Else
MakeSQLText = «‘» & Replace(data, «‘», «»») & «‘»
End If
End Function
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
‘ Let’s retrieve the data from the SQL Server table with the same name as the sheet
bIgnoreChange = True
Set con = New ADODB.Connection
con.Provider = «sqloledb»
sConnectionString = «Server=D90SC6Q1SQLEXPRESS;Database=BIClients;UID=BIClients;Pwd=Rumbl31nJungl3»
con.Open sConnectionString
‘ Clean up old Primary Key
While (pk.Count > 0)
pk.Remove 1
Wend
‘ Try to retrieve the primary key information
On Error GoTo NoCon
Set rs = con.Execute(«SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME WHERE tc.CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND tc.TABLE_NAME
= ‘» & Sh.name & «‘»)
‘ Fill up the primary key infomration
While (Not rs.EOF)
pk.Add CStr(rs(0))
rs.MoveNext
Wend
‘ Clean up the sheet’s contents
Sh.UsedRange.Clear
‘ Now get the table’s data
Set rs = con.Execute(«SELECT fkGroupID,fkProjectID,[Outage Start Date],[Outage Stop Date],[Man Hour Lost],[Outage Cost],[fkReasonCategoryId] FROM » & Sh.name)
‘ Set the name of the fields
Dim TheCells As Range
Set TheCells = Sh.Range(«A1»)
For i = 0 To rs.Fields.Count — 1
TheCells.Offset(0, i).Value = rs.Fields(i).name
Next i
‘ Get value for each field
nRow = 1
While (Not rs.EOF)
For i = 0 To rs.Fields.Count — 1
TheCells.Offset(nRow, i).Value = rs(i)
Next
rs.MoveNext
nRow = nRow + 1
Wend
nRecordCount = nRow — 1
bIgnoreChange = (pk.Count = 0) And (nRecordCount > 0)
Exit Sub
NoCon:
con.Close
Set con = Nothing
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
‘ No loops, and don’t do nothing if there’s no connection
If bIgnoreChange Or con Is Nothing Then
Exit Sub
End If
‘ Is something different?
If (Target.Value = oldValue) Then
‘ No change
oldValue = Application.ActiveCell.Value
Exit Sub
End If
‘ Don’t allow changes in the column names or outside of the table borders
‘If Target.Row < 2 Or Sh.Cells(1, Target.Row).Text = «» Or Sh.Cells(1, Target.Column) = «» Or (Target.Row > nRecordCount + 1) Then
‘ Target.Value = oldValue
‘oldValue = Application.ActiveCell.Value
‘MsgBox «You can only edit items inside the table»
‘Exit Sub
‘End If
‘ Is this change is in a primary key column — if so, we can’t edit it
If (IsInPrimaryKey(Sh.Cells(1, Target.Column).Text)) Then
Target.Value = oldValue
oldValue = Application.ActiveCell.Value
MsgBox «This column is a part of the primary key, so it cannot be changed»
Exit Sub
End If
‘ Build the primary key from the data in this row
Dim Names As Range
Set Names = Sh.Range(«A1»)
nColumn = 0
sWhere = «»
While (Names.Offset(0, nColumn).Text <> «»)
If (IsInPrimaryKey(Names.Offset(0, nColumn).Text)) Then
If (sWhere <> «») Then
sWhere = sWhere & » AND «
End If
sWhere = sWhere & Sh.Cells(1, nColumn + 1).Text & » = » & MakeSQLText(Sh.Cells(Target.Row, nColumn + 1))
End If
nColumn = nColumn + 1
Wend
‘ Update the server!
sSQL = «UPDATE » & Sh.name & » SET » & «[» & Sh.Cells(1, Target.Column).Text & «]» & » = » & MakeSQLText(Target.Text) & » WHERE » & sWhere
con.Execute sSQL
oldValue = Application.ActiveCell.Value
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If (Not bIgnoreChange) Then
‘ Remember the old value
oldValue = Application.ActiveCell.Value
End If
End Sub
Santt
Содержание
- VBA-SQL UPDATE/INSERT/SELECT to/from Excel worksheet
- 2 Answers 2
- INSERT INTO statement from Excel to SQL Server Table using VBA
- 2 Answers 2
- HTNet
- Inserting Data Into MySQL From Excel Using VBA
- Connecting to the Database Server and Selecting the Correct Database
- Оператор INSERT INTO из Excel в таблицу SQL Server с использованием VBA
VBA-SQL UPDATE/INSERT/SELECT to/from Excel worksheet
In a nutshell: I’m making a scheduler for my client and, due to constraints, it needs to be in a single excel file (as small as possible). So one worksheet works as the UI and any others will be tables or settings.
I’m trying to use SQL (to which I’m new) to work with the schedule data on a single worksheet (named «TblEmpDays»). So I need to add/update and retrieve records to/from this worksheet. I was able to get a SELECT query to work with some arbitrary data (and paste to a Range). However, I’m not able to get INSERT or UPDATE to work. I’ve seen it structured as INSERT INTO [
$] ( ) VALUES ( ); . However this gives me a run-time error «‘-2147217900 (80040e14)’ Syntax error in INSERT INTO statement.
I’m using VBA to write all of this and I made an SQL helper class to make the query execution easier.
To clarify, my question is: How do I need to construct the INSERT and UPDATE queries? What am I missing? I’m trying to post as much related info as possible, so let me know if I missed anything.
Class SQL:
Executing function:
I’ve looked all over an can’t find a solution. I’m sure I just haven’t searched the right phrase or something simple.
2 Answers 2
I’m posting the solution here since I can’t mark his comment as the answer.
Thanks to @Jeeped in the comments, I now feel like an idiot. It turns out three of my field names were using reserved words («name», «date», and «in»). It always seems to be a subtle detail that does me in.
I renamed these fields in my worksheet (table) and altered the appropriate code. I also had to Cast the input strings into the proper data types. I’m still working the rest of the details out, but here’s the new query:
I needed the CDate() (instead of the #*#) so I could pass in a string. So CDate(‘ ‘) instead of # #
Consider using a relational database as backend instead of a worksheet for your project. You can continue to use the UI spreadsheet as a frontend. As a Windows product, the Jet/ACE SQL Engine can be a working solution plus it allows multiple user with simultaneous access (with record-level locking). Additionally, Jet/ACE comes equipped with its own SQL dialect for Database Definition Language (DDL) and Database Maniupulation Language (DML) procedures. And Excel can connect to Jet/ACE via ADO/DAO objects. The only difference of Jet/ACE compared to other RDMS is that it is a file level database (not server) and you cannot create a database using SQL. You must first create the database file using VBA or other COM defined language.
Источник
INSERT INTO statement from Excel to SQL Server Table using VBA
The code below is meant to simply add rows of information from an Excel sheet to a table in SQL Server. It is tediously written where it goes row by row and cell by cell. It runs with no error pop-ups, but when I check the table for my data, there is nothing there.
I have been querying in SQL to check by using a WHERE clause and the ‘Analyst’ field should match my name. Nothing pops up.
Why is my data not showing up in the table? AND I am open to hear anyone’s suggestions on better ways to do this. Thanks!
2 Answers 2
Reconsider your heavy Excel migration to SQL Server for several solutions:
SQL Server: Save Excel data into text format (.txt, .tab, .csv) and use any number of SQL Server’s bulk handling operations: bcp utility, OPENROWSET, OPENDATASOURCE, import wizard, and BULK INSERT. Place this process in a stored procedure to be run inside database.
Below are two equivalent OPENROWSET examples on Excel workbooks where no individual values are handled but whole table operations:
MS Access: Use Excel’s database sibling, Access, as medium between the source and destination sources. Specifically, have Excel sheet and SQL Server table as linked tables where you can run a simple append query:
MS Excel: If you have to run in Excel, use parameterization with ADO Command object and avoid the need to concatenate VBA values to SQL code with numerous quote enclosures.
Источник
HTNet
Inserting Data Into MySQL From Excel Using VBA
seun asked in an old post of mine, Interfacing with MySQL via Excel; whether it’s possible to submit data from Excel into MySQL.
Yes, it is very much possible to do this. In fact, I’ve written a tutorial on how to do this with the help of VBA .
First, we create the table that we will use to store the data. The SQL statement below will create our sample table called tutorial. Just copy and paste it into your favourite MySQL IDE or phpMyAdmin.
Now that we’ve created the table, it’s time to store some data in it. The data must come from a source. In this example, I’ve created a list of book titles, along with the author and price of each book. Just copy the table below and paste it into an Excel worksheet.
«
Title | Author | Price |
---|---|---|
How to Win Friends and Influence People | Dale Carnegie | 7.99 |
The Magic of Thinking Big | David Schwartz | 10.17 |
The Richest Man in Babylon | George S. Clason | 6.99 |
As a Man Thinketh | James Allen | 9.95 |
The Power of Your Subconcious Mind | Dr. Joseph Murphy | 7.49 |
The Magic of Believing | Claude M. Bristol | 6.99 |
It Works | R.H. Jarrett | 3.00 |
Write It Down, Make It Happen: Knowing What You Want and Getting It | Henriette Anne Klauser | 10.52 |
The Attractor Factor: 5 Easy Steps For Creating Wealth (Or Anything Else) From the Inside Out | Joe Vitale | 11.53 |
The Science of Getting Rich | Wallace D. Wattles | 11.20 |
Now rename that sheet as Books. If you haven’t displayed your Visual Basic and Control Toolbox toolbars yet, now is a good time to do so. Go to the View top menu and navigate to Toolbars. Make sure Visual Basic and Control Toolbox are checked.
I prefer to place the toolbars at the top panel area so they’re out of the way of my Excel spreadsheet. You might want to do the same.
Next, click on the Properties icon of the Control Box toolbar and set the name of the Booksworksheet as wsBooks. You’ll get something like the screenshot below:
Now it’s on to some programming. But before we even start typing a single line of code, we need to understand what we’re trying to achieve with our code:
- Connect to the local MySQL database server
- Use the demo database
- Insert each line of the Books table into the tutorial database we created earlier
Connecting to the Database Server and Selecting the Correct Database
As we will be using VBA to perform our data insertion, we need a method to connect to the database server and ensure we’ve selected the correct database where the data will be inserted into.
There are three components necessary for us to perform MySQL database manipulation using VBA:
- MySQL Connector/ODBC
- Microsoft ActiveX Data Objects (ADO) Library
- The correct connection string to access the MySQL database
For this tutorial, I’m using MySQL Connector/ODBC 5.1. You can download it here. For Windows users, grab the MSI Installer version and just double click the file and go through the installation screen.
You’ll also need to reference to the Microsoft ActiveX Data Objects Library in your Excel Workbook. Fire up the Visual Basic Editor using Alt-F11. Go to the Tools top menu item of the Visual Basic Editor and choose References.
In the list of references, check the Microsoft ActiveX Data Objects 2.8 Library. Refer to the following screenshot:
Next, we will then start coding. The first thing we should do is to write a Sub procedure to connect to the database. This will be done using an ADODB connection.
First we need to declare the variable for the ADODB connection. Make sure you’ve double-clicked the wsBooks worksheet in the Project Explorer (if you can’t see it, press Ctrl-R). It should bring out a code window for that sheet.
In that sheet, enter the following code:
You should replace yourdatabase, yourdbusername and yourdbpassword with your database name, your database username and the database password accordingly.
Test your ConnectDB Sub procedure by putting the cursor anywhere between the Sub statement and press F5 (this runs the Sub procedure). If an error popup appears, check that your MySQL service is running and that you’ve referenced to the Microsoft ActiveX Data Objects 2.8 Library.
Once the ConnectDB Sub procedure is working, we will code the Sub procedure to perform data insertion. Before that, we need to create a data sanitizing function to escape single quotes before inserting them into the database. This is necessary because improper quote escaping will cause data insertion to fail.
Here are the codes for the esc function that will escape single quotes from data to be inserted:
And now for the Sub procedure to perform data insertion:
Now run the InsertData Sub procedure and you will see that it will insert the data from line 2 to line 11 of the Books worksheet into the tutorial table.
Hope this tutorial has given you a basic understanding on how to insert data into a MySQL database from Microsoft Excel using VBA. If you have any questions, just drop a comment below.
Источник
Оператор INSERT INTO из Excel в таблицу SQL Server с использованием VBA
Приведенный ниже код предназначен для простого добавления строк информации из листа Excel в таблицу в SQL Server. Это утомительно написано там, где идет строка за строкой и ячейка за ячейкой. Он работает без всплывающих окон с ошибками, но когда я проверяю таблицу на предмет своих данных, там ничего нет.
Я выполнял запрос в SQL для проверки с помощью предложения WHERE, и поле «Аналитик» должно соответствовать моему имени. Ничего не всплывает.
Почему мои данные не отображаются в таблице? А ТАКЖЕ Я открыт для любых предложений о лучших способах сделать это. Спасибо!
Вы уже создали strSQL, используя пустые переменные, и после этого никогда не обновляете его, так что он остается таким.
Вам нужно вставлять значения полей каждый раз в цикле.
СПАСИБО @TimWilliams! Работает как сон на листе с 84 строками. Однако, когда я начал использовать его на листе с более чем 30 тысячами строк, он дал мне следующую ошибку в DBCONT.Execute strSQL: метод «execute» объекта «_connection» не прошел. Он прошел около 199 строк и успешно их загрузил. Затем я нажал DEBUG и начал выполнять код вручную. Он фактически продолжал работать и загружать каждый раз, но выдавал мне сообщение об ошибке прямо в том же месте. Это происходит, если сумма слишком большая?
Эту проблему удалось решить, добавив некоторый код DBCONT.commandtimeout DBCONT.connectiontimeout и позволив ему работать. Сценарий такой: у нас есть группа аналитиков, которые работают над отчетами. Чтобы отслеживать аудиты, нам нужны эти данные и сначала нужно добавить некоторую информацию для ведения учета. Затем аналитик должен загрузить его на сервер. Следовательно, возможность использовать тот же инструмент Excel, который я создал, а не сохранение файла, а затем открытие SQL и добавление другого способа — это не тот способ, которым его просили.
Пересмотрите свою тяжелую миграцию Excel на SQL Server для нескольких решений:
SQL Server: сохранение данных Excel в текстовом формате (.txt, .tab, .csv) и использование любого количества операций массовой обработки SQL Server: утилита bcp, ОТКРЫТЬ, OPENDATASOURCE, мастер импорта и ОБЪЕМНАЯ ВСТАВКА. Поместите этот процесс в хранимую процедуру для запуска в базе данных.
Ниже приведены два эквивалентных примера OPENROWSET в книгах Excel, в которых обрабатываются не отдельные значения, а операции всей таблицы:
MS доступ: использовать родственную базу данных Excel, Access, в качестве посредника между исходным и целевым источниками. В частности, используйте лист Excel и таблицу SQL Server как связанные таблицы, где вы можете выполнить простой запрос на добавление:
MS Excel: если вам нужно работать в Excel, используйте параметризацию с помощью Объект команды ADO и избегайте необходимости объединять значения VBA в код SQL с многочисленными вложениями кавычек.
Спасибо, @SMeaden! Если не OP, я надеюсь, что это поможет будущим читателям.
Это круто! Могу ли я, используя параметризацию, по-прежнему использовать переменные, которые у меня есть в strSQL, которые идут со значениями VALUES, а затем создавать новые переменные для параметров? Я просто вижу «?» И не уверен, что это значит.
Qmark’ы, ?, являются заполнителями, которые позже связываются позициями со строками .Parameters.Append. Значения диапазона ячеек Excel находятся в последнем аргументе метода .CreateParameter(Name, Type, Direction, Size, Value). Параметризация отделяет SQL от уровня приложения, здесь это VBA. Подготовленную выписку трогать не нужно.
Привет, ваш код работает отлично, спасибо, у меня есть небольшое улучшение, чтобы легко настроить код для других таблиц. вместо создания всех имен столбцов и? значений для strSQL, просто создайте массив имен столбцов «mycolumns = array (» col1 «,» col2 «)» и зациклите весь массив, чтобы создать строку имен столбцов с разделителем «], [» и списком «?» для значений используйте эти 2 строки в strSQL. вы также можете использовать его в параметре append, если вы загружаете последовательные столбцы, таким образом вы получаете более надежный код, легко вписываете любую таблицу и гораздо меньше кода
Источник
seun asked in an old post of mine, Interfacing with MySQL via Excel; whether it’s possible to submit data from Excel into MySQL.
Yes, it is very much possible to do this. In fact, I’ve written a tutorial on how to do this with the help of VBA.
First, we create the table that we will use to store the data. The SQL statement below will create our sample table called tutorial. Just copy and paste it into your favourite MySQL IDE or phpMyAdmin.
CREATE TABLE IF NOT EXISTS `tutorial` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) NOT NULL,
`author` varchar(255) NOT NULL,
`price` float(4,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Now that we’ve created the table, it’s time to store some data in it. The data must come from a source. In this example, I’ve created a list of book titles, along with the author and price of each book. Just copy the table below and paste it into an Excel worksheet.
Title | Author | Price |
---|---|---|
How to Win Friends and Influence People | Dale Carnegie | 7.99 |
The Magic of Thinking Big | David Schwartz | 10.17 |
The Richest Man in Babylon | George S. Clason | 6.99 |
As a Man Thinketh | James Allen | 9.95 |
The Power of Your Subconcious Mind | Dr. Joseph Murphy | 7.49 |
The Magic of Believing | Claude M. Bristol | 6.99 |
It Works | R.H. Jarrett | 3.00 |
Write It Down, Make It Happen: Knowing What You Want and Getting It | Henriette Anne Klauser | 10.52 |
The Attractor Factor: 5 Easy Steps For Creating Wealth (Or Anything Else) From the Inside Out | Joe Vitale | 11.53 |
The Science of Getting Rich | Wallace D. Wattles | 11.20 |
Now rename that sheet as Books. If you haven’t displayed your Visual Basic and Control Toolbox toolbars yet, now is a good time to do so. Go to the View top menu and navigate to Toolbars. Make sure Visual Basic and Control Toolbox are checked.
I prefer to place the toolbars at the top panel area so they’re out of the way of my Excel spreadsheet. You might want to do the same.
Next, click on the Properties icon of the Control Box toolbar and set the name of the Booksworksheet as wsBooks. You’ll get something like the screenshot below:
Now it’s on to some programming. But before we even start typing a single line of code, we need to understand what we’re trying to achieve with our code:
- Connect to the local MySQL database server
- Use the demo database
- Insert each line of the Books table into the tutorial database we created earlier
Connecting to the Database Server and Selecting the Correct Database
As we will be using VBA to perform our data insertion, we need a method to connect to the database server and ensure we’ve selected the correct database where the data will be inserted into.
There are three components necessary for us to perform MySQL database manipulation using VBA:
- MySQL Connector/ODBC
- Microsoft ActiveX Data Objects (ADO) Library
- The correct connection string to access the MySQL database
For this tutorial, I’m using MySQL Connector/ODBC 5.1. You can download it here. For Windows users, grab the MSI Installer version and just double click the file and go through the installation screen.
You’ll also need to reference to the Microsoft ActiveX Data Objects Library in your Excel Workbook. Fire up the Visual Basic Editor using Alt-F11. Go to the Tools top menu item of the Visual Basic Editor and choose References.
In the list of references, check the Microsoft ActiveX Data Objects 2.8 Library. Refer to the following screenshot:
Next, we will then start coding. The first thing we should do is to write a Sub procedure
to connect to the database. This will be done using an ADODB connection.
First we need to declare the variable for the ADODB connection. Make sure you’ve double-clicked the wsBooks worksheet in the Project Explorer (if you can’t see it, press Ctrl-R). It should bring out a code window for that sheet.
In that sheet, enter the following code:
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=yourdatabase;" & _
"USER=yourdbusername;" & _
"PASSWORD=yourdbpassword;" & _
"Option=3"
End Sub
You should replace yourdatabase, yourdbusername and yourdbpassword with your database name, your database username and the database password accordingly.
Test your ConnectDB Sub procedure by putting the cursor anywhere between the Sub statement and press F5 (this runs the Sub procedure). If an error popup appears, check that your MySQL service is running and that you’ve referenced to the Microsoft ActiveX Data Objects 2.8 Library.
Once the ConnectDB Sub procedure is working, we will code the Sub procedure to perform data insertion. Before that, we need to create a data sanitizing function to escape single quotes before inserting them into the database. This is necessary because improper quote escaping will cause data insertion to fail.
Here are the codes for the esc function
that will escape single quotes from data to be inserted:
Function esc(txt As String)
esc = Trim(Replace(txt, "'", "'"))
End Function
And now for the Sub procedure to perform data insertion:
Dim rs As ADODB.Recordset
Private Sub InsertData()
Set rs = New ADODB.Recordset
ConnectDB
With wsBooks
For rowCursor = 2 To 11
strSQL = "INSERT INTO tutorial (author, title, price) " & _
"VALUES ('" & esc(.Cells(rowCursor, 1)) & "', " & _
"'" & esc(.Cells(rowCursor, 2)) & "', " & _
esc(.Cells(rowCursor, 3)) & ")"
rs.Open strSQL, oConn, adOpenDynamic, adLockOptimistic
Next
End With
End Sub
Now run the InsertData Sub procedure and you will see that it will insert the data from line 2 to line 11 of the Books worksheet into the tutorial table.
Hope this tutorial has given you a basic understanding on how to insert data into a MySQL database from Microsoft Excel using VBA. If you have any questions, just drop a comment below.
Tags: Microsoft, MySQL, Smoking