Excel VBA to Create SQL Table - sql

I have found the following code which is supposed to create an SQL table within an SQl Database.
The database is specified in dbpath and the table to be created is in tblname.
However when I run this code I have a problem connecting to right SQL database.
For example if I specify dbpath as "WIN2k8\Test\ABC" ie the machine name is WIN2k8, sql instance is Test database is ABC.
For some reason it keeps picking up the dbpath as where I have saved the Excel workbook then WIN2k8\test\abc.
Can somebody help?
Dim dbConnectStr As String
Dim Catalog As Object
Dim cnt As ADODB.Connection
Dim dbPath As String
Dim tblName As String
'Set database name in the Excel Sheet
dbPath = ActiveSheet.Range("B1").Value 'Database Name
tblName = ActiveSheet.Range("B2").Value 'Table Name
dbConnectStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ";"
'Create new database using name entered in Excel Cell ("B1")
Set Catalog = CreateObject("ADOX.Catalog")
Catalog.Create dbConnectStr
Set Catalog = Nothing
'Connect to database and insert a new table
Set cnt = New ADODB.Connection
With cnt
.Open dbConnectStr
.Execute "CREATE TABLE tblName ([BankName] text(50) WITH Compression, " & _
"[RTNumber] text(9) WITH Compression, " & _
"[AccountNumber] text(10) WITH Compression, " & _
"[Address] text(150) WITH Compression, " & _
"[City] text(50) WITH Compression, " & _
"[ProvinceState] text(2) WITH Compression, " & _
"[Postal] text(6) WITH Compression, " & _
"[AccountAmount] decimal(6))"
End With
Set cnt = Nothing

The Jet.OLEDB provider is for MS Access. Try using a SQL Server connection string if that is what you are trying to connect to. You can find the different types of connections strings at http://www.connectionstrings.com/.
Hope that helps

You could also try thy udl file trick described at the following location - You can also try to the udl file approach to get your connection string - http://msdn.microsoft.com/en-us/library/aa140076%28office.10%29.aspx

Related

VBA to query field contents in CSV

I'm struggling with ADO connections/recordsets.
My problem statement is: a function that will return the first value of a chosen field, in a chosen .csv file.
I am doing this to identify variably-named .csv files before adding the data to the relevant tables in a database. I am making the assumption that this field is always present and that either it is consistent throughout the file, or only relevant ones are grouped (this is controlled higher up the chain and is certain enough).
My code is being run as part of a module in an MS Access database:
Public Function GetFirstItem(File As Scripting.File, Field As String)
Dim Conn As ADODB.Connection, Recordset As ADODB.Recordset, SQL As String
Set Conn = New ADODB.Connection
Set Recordset = New ADODB.Recordset
'Microsoft.ACE.OLEDB.16.0 / Microsoft.Jet.OLEDB.4.0
Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=""" & File.ParentFolder & _
"""; Extended Properties=""text;HDR=Yes;FMT=Delimited;"";"
SQL = "SELECT " & Field & " FROM """ & File.Name & """ LIMIT 1"
Debug.Print Conn.ConnectionString
Debug.Print SQL
Conn.Open
Recordset.Source = SQL
Recordset.ActiveConnection = Conn.ConnectionString
Recordset.Open
Recordset.MoveFirst
'GetFirstItem = Recordset!Questionnaire
Recordset.Close
Conn.Close
Set Recordset = Nothing
Set Conn = Nothing
End Function
ConnectionString = Provider=Microsoft.ACE.OLEDB.16.0;Data Source="D:\Documents\Jobs\TestPath"; Extended Properties="text;HDR=Yes;FMT=Delimited;";
Field = Questionnaire
SQL = SELECT Questionnaire FROM "test.csv" LIMIT 1
I get an error on Recordset.Open of:
This may be (is probably) down to a complete lack of understanding of how ADO connections/recordsets work. I have tried sans-quotes and it complains about a malformed FROM expression. Additionally, once this hurdle is overcome I am unsure of the syntax of how to return the result of my query. If there is a better way of doing this I am all ears!
Thanks.
In Access you don't need ADO library to query a CSV file:
Public Function GetFirstItem(File As Scripting.File, Field As String) As String
Dim RS As DAO.Recordset, SQL As String
SQL = "SELECT TOP 1 [" & Field & "]" _
& " FROM [" & File.Name & "]" _
& " IN '" & File.ParentFolder & "'[Text;FMT=CSVDelimited;HDR=Yes];"
Debug.Print SQL
Set RS = CurrentDb.OpenRecordset(SQL)
GetFirstItem = RS(0)
RS.Close
Set RS = Nothing
End Function
Usage:
?GetFirstItem(CreateObject("Scripting.FileSystemObject").getfile("c:\path\to\your\file.csv"), "your field")

Allow others on shared drive to use access odbc connection

I have an Access file with ADD and UPDATE queries that is linked to an SQL database of some sort (Orderwise). I'm building the reports and things, but someone else in our company will end up using it - possibly a variety of people - therefore I've put it on a Shared Drive.
However, when I access it from another computer (tried to demonstrate it to the Ops manager) it loses the connection to the SQL database, despite both computers having access to that drive too. I'm new to this but I think the ODBC file / connection it relies on is somewhere in the computer that built the database - the error message is ODBC connection to 'Orderwise 2' failed..
I've tried researching it but haven't found anything very conclusive, it seems to involve .mdb files but I don't know where those are, and hunting through the control panel settings thing doesn't give an option to move the odbc to a shared drive.
How can I share this database so everyone on the shared drive can use the live data connection?
Below is code to connect SQL Database and run commands.
Private Sub cmdTest_Click()
'Add reference Microsoft ActiveX Data Objects 2.1 Library
'Fix SQL Server Connection ERROR! See below link
'https://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/
'Declare variables'
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordset As ADODB.Recordset
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Dim strEmpID As String, strEmpName As String
Dim JoiningDate As Date
Dim eSalary As Integer
Dim myRate As Double
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=192.168.0.150;User ID=sa;Password=saDBpassword;"
objMyConn.Open
'Another provider
'Provider=sqloledb;Data Source=192.168.0.150,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=myUsername;Password=myPassword;
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
' Insert data to SQL Database table.
strEmpID = InputBox("Enter Employee ID:", "Employee ID", "HO-300")
strEmpName = InputBox("Enter Employee Name:", "Employee Name", "Mr. SQL")
JoiningDate = InputBox("Enter Joining Date:", "Joining Date", Date)
eSalary = InputBox("Enter Salary:", "Salary", 10000)
myRate = InputBox("Enter Rate:", "Rate", 11.11)
objMyCmd.CommandText = "INSERT INTO [TestDB].[dbo].[tblEmpInfo] (EmpID, EmpName, jDate, Salary, HourRate) Values('" _
& strEmpID & "', '" _
& strEmpName & "', '" _
& JoiningDate & "', " _
& eSalary & ", " _
& myRate & ")"
objMyCmd.CommandType = adCmdText
objMyCmd.Execute 'Execute SQL command
End Sub
You have to add ActiveX Data Objects 2.5 Library to reference. I am using MS-Access-2013. Object reference may varies depending on MS-Access versions.
Please read this article carefully to troubleshoot network service barrier. SQL Server Fix Error.

How to append data from a SQL Server table to an Access table?

I am trying to write a query in MS access to open a connection to a local SQL Server and then to import select tables into MS Access.
My code runs until the Cn.Execute statement. I get
Run-time error '-2471765 (80040e37)' [Microsoft][ODBC SQL Server Driver][SQL Server] Invalid Object Name 'dbo_SQLServertable'.
I need to import additional tables so I need a code that will work when I change table names.
Private Sub Command28_Click()
Dim Cn As ADODB.Connection
Dim Server_Name As String
im Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "" ' Enter your server name here
Database_Name = "Test" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";"
Cn.Execute "INSERT INTO Access Table SELECT dbo_SQLServerTable.* FROM dbo_SQLServerTable;"
Set rs = Nothing
Cn.Close
Set Cn = Nothing
I made changes and I get a new error message
Run-time error '-2147216900 (80040e14)' [Microsoft][ODBC SQL Server Driver][SQL Server] Cannot Insert the value NULL into column 'DiagnosisOrdinal', table 'Office.dbo.Test' column does not allow nulls. Insert fails.
It appears that my insert statement is still referencing (or trying to reference) a table in the SQL server. 'Office' is the database name that I am pulling from.
Do I have to close the connection and then paste the data into my local Access table? Will I then have to re-open and close the connection if I want to do this for multiple tables?
I changed my execute statement from
Cn.Execute "INSERT INTO Access Table SELECT dbo_SQLServerTable.* FROM dbo_SQLServerTable;"
to
Cn.Execute "INSERT INTO Test(VisitID, Provider) SELECT VisitID, Provider FROM dbo.SQLServerTable;"
Least amount of code I can think of is to use a pass-through query.
Setup a PT query to the server database in question.
Then your code to create a new table in access would look like:
Sub TestImport()
Dim strSQL As String
With CurrentDb.QueryDefs("qryPassR")
.SQL = "select * from tblHotels"
End With
Dim strLocalTable As String
strLocalTable = "zoo"
CurrentDb.Execute "select * into " & strLocalTable & " FROM qryPassR"
End Sub
The above of course assumes you setup the connection to sql server (one database) when you created the PT query. The above approach is nice since you don't mess around with connection strings in code.
However, given that you need (want) to specify the database (and likely server), then above becomes this:
Sub TestImport2()
Dim strSQL As String
Dim strServer As String
Dim strDatabase As String
Dim strUser As String
Dim strPass As String
strServer = ""
strDatabse = ""
strUser = ""
strPass = ""
Dim strLocalTable As String
Dim strServerTable As String
With CurrentDb.QueryDefs("qryPassR")
.Connect = dbCon(strServer, strDatabase, strUser, strPass)
.SQL = "select * from " & strServerAble
End With
CurrentDb.Execute "select * into " & strLocalTable & " FROM qryPassR"
End Sub
The above uses a "handy" function to create your connection string.
That function is as follows:
Public Function dbCon(ServerName As String, _
DataBaseName As String, _
Optional UserID As String = "", _
Optional USERpw As String, _
Optional APP As String = "Office 2010", _
Optional WSID As String = "Import") As String
' returns a SQL server conneciton string
dbCon = "ODBC;DRIVER=" & SQLDRIVER & ";" & _
"SERVER=" & ServerName & ";" & _
"DATABASE=" & DataBaseName & ";"
If UserID <> "" Then
dbCon = dbCon & "UID=" & UserID & ";" & "PWD=" & USERpw & ";"
End If
dbCon = dbCon & _
"APP=" & APP & ";" & _
"WSID=" & WSID & ";" & _
"Network=DBMSSOCN"
End Function
Edit
Poster has asked for solution to append data into a EXISTING table.
In that case, simply change this:
CurrentDb.Execute "select * into " & strLocalTable & " FROM qryPassR"
to
CurrentDb.Execute "INSERT INTO " & strLocalTable & " SELECT * FROM qryPassR"
You don't want the table prefix in your SELECT from the SQL table. Just do SELECT * FROM dbo_SQLServerTable; Best practice, though, is not to use SELECT * but rather specify the columns in case the table schemas ever change.
There's a few suggestions for this particular issue
Pass thru queries
Linked Tables from SQL Server. Youll prolly have to set up a dsn file which isnt too terribly difficult.
Or handle it directly in SQL Server Insert into Access from SQL Server
ODBC connection via VBA (what youre doing and seemingly the most convoluted)
All of these approaches will work fine. I suggest linked tables so you dont duplicate data but thats a cinsderation fro you since I dont knwo the requirements of the project.
dbo_SQLServerTable is an Access table name, not SQL server table name. Because you already created the linked table dbo_SQLServerTable, you can use the following VBA code.
Currentproject.connection.execute "INSERT INTO MyAccessTable(fld1, fld2, fld3) SELECT fld1, fld2,fld3 FROM dbo_SQLServerTable"
There is no need to create connection object in VBA code. Currentproject.connection is always available to be referenced.

Can't insert records from Excel to SharePoint

Currently I am suffering Excel ADO issue.
Here is the thing taht
I was trying to insert some records
from "Excel table" to "SharePoint list" Using ADO connection.
But failed (Can't recognize Excel table in SQL Statement)
Dim SQL As String
Dim CN As New ADODB.Connection
Dim OLEDB As String
Dim LIST As String
Dim SITE As String
LIST = "{EE028282-3D7E-4D37-93EE-50FB69C4432C}"
SITE = "https://asml.sharepoint.com/teams/FFKR_DUV_YS_Installation_and_Relocation/Product"
OLEDB = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;" & _
"DATABASE=" & SITE & ";" & _
"LIST=" & LIST & ";"
Set CN = New ADODB.Connection
CN.Open OLEDB
SQL = SQL & "INSERT INTO Schedule_DB (NAME,TYPE_W) "
SQL = SQL & "SELECT * "
SQL = SQL & "FROM [" & ThisWorkbook.FullName & "].[S_RAW$] "
CN.Execute CommandText:=SQL
CN.Close
If I run it I got error ->
Error image
I have already check the miss-spell, and the amount of item is too much, so I would prefer to process it as a one SQL statement.
"Excel to Excel" works well But still have no ideas for "Excel to SharePoint List".
Please share your advice.
When you want to read data from your Excel sheet you need to have a ADODB.Connection with Read permission, then to write data to your SharePoint List you need to have another ADODB.Connection with Write permission.
Note: You can't transport your whole data in that way, You can generate a big command with whole data then use it or generate command for each record of your Excel data.
About your exception it is simply says it can't find your sheet name in SharePoint Lists.
A sample to guide you can be something like this:
Dim cnnXl As New ADODB.Connection
Dim rsXl As New ADODB.Recordset
Dim cnnShP As New ADODB.Connection
conStrXl = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\yourExcel.xlsx';" & _
"Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;"";"
commandXl = "SELECT [Field1], [Field2] FROM [Worksheet$$A1:D7] WHERE [Thing1] > 1"
conStrShP = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;" & _
"DATABASE=yourSite;LIST={yourListCLSID};"
Then open cnnXl and run commandXl and read data to rsXl.
Then open cnnShP and loop over rsXl records and create your commandShP and execute it.

Excel Insert Into Access Table from Excel defined Table with a Where Clause

A little stuck. I have a an excel table with lets say the following columns
[Date],[Name],[PostCode],[City]
And an access table with the same column names.
I'm trying to insert the excel data table into the access table but want to apply a WHERE clause so that it ignores dates already in the access table.
I can happily inset all data into the access table but cannot apply a WHERE clause successfully ignore the existing dates. And annoyingly I cant reference the actual table name correct so I am referencing the sheet (but works fine).
This is the code I have so far:
Sub TestInsert()
Dim cnn As ADODB.Connection
Dim dbPath As String
Dim xlPath As String
Dim uSQL As String
dbPath = "C:\Test\TestDB.accdb"
xlPath = "C:\Test\TestXL.xlsm"
'Set Connection string
Set cnn = New Connection
cnnstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
'Open connection to db
cnn.Open cnnstr
uSQL = "INSERT INTO tbl_ApolloBrochurewareReportTEST " _
& "SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=" & xlPath & "].[Sheet1$]"
cnn.Execute uSQL
cnn.Close
End Sub
Any input or knowledge would be great, thank you.
You should be able to expand the SQL expression:
uSQL = "INSERT INTO tbl_ApolloBrochurewareReportTEST " _
& "SELECT * FROM [Excel 12.0;HDR=YES;DATABASE=" & xlPath & "].[Sheet1$] As T " & _
"WHERE T.Date NOT IN (SELECT [Date] FROM tbl_ApolloBrochurewareReportTEST)"