import data from excel 2003 to dataTable - excel

I am importing excel worksheets to a datagridview using the following code:
Private Sub Browsimportbtn_Click(sender As Object, e As EventArgs) Handles Browsimportbtn.Click
Dim textpath As String
Dim textpath1 As String
Dim opf As New OpenFileDialog
If opf.ShowDialog = 1 Then
textpath = opf.FileName
textpath1 = opf.SafeFileName
textpath1 = textpath1.Remove(textpath1.Length -4,4)
Dim cnexcell As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & textpath & "; Extended Properties = ""Excel 12.0 Xml;HDR=YES"";")
Dim cmdE As New OleDbCommand("SELECT * FROM Feuil1", cnexcell)
Try
Dim daoledb As New OleDbDataAdapter
Dim dset As New DataSet
daoledb.SelectCommand = cmdE
daoledb.Fill(dset, "Feuil1")
DGVmodele.DataSource = dset.Tables("Feuil1")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
The code above is working well with .XLSX files (office 2007,2010...) but do not with .XLS and i don't know where is the issue.
Any suggestions?

The issue is in the connectionstring.
You are specifying the Excel 12 as a version in the connection string which is related to 2007 or higher. Try using this function to build the connectionstring
Public Function BuildConnectionString(Byval m_strExcelPath as String) As String
If m_strExcelPath.Substring(m_strExcelPath.LastIndexOf(".")).ToLower = ".xlsx" Then
Return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & m_strExcelPath & ";Excel 12.0;HDR=YES;IMEX=1"
Else
Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & m_strExcelPath & ";Excel 8.0;HDR=YES;IMEX=1"
End If
End Function

Try using this instead.
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & m_strExcelPath & ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"
It is unadvisable to use the JET OLEDB because it is outdated. If you really want to use it, you might need to reinstall Access Database Engine 2003.
Also, I heard there's also a bug regarding this.

Related

Microsoft.ACE.OLEDB.12.0; possible connection string formatting error causes "Could not find installable ISAM file" error?

The macro I'm having problem with is written in Word VBA Editor and it's lunched from Word.
It's goal is to link into Excel .xlsm file (treated as a customers database) via Microsoft.ACE.OLEDB.12.0; connection and, without even opening the file, read whole sheet from that file (sheet name = "data") into a dynamic array which will be searched later.
I have some code written to do this, but it crashes on the connection string, probably because I don't know how to format it - these quotes I mean, I just don't understand how are they placed and why.
Most important thing is that the code is written in Word VBA Editor and it's lunched from Word .docm file.
Option Explicit
Private Sub UseADOSelect()
Dim connection As New ADODB.connection
Dim recSet As New ADODB.Recordset 'All the results of the query are placed in a record set;
Dim exclApp As Excel.Application
Dim exclWorkbk As Excel.Workbook
Dim mySheet As Excel.Worksheet
Dim wordDoc As Word.Document
Dim cntCntrl As ContentControl
Dim strPESELfromWord As String
Dim strQuery As String
Dim intWiersz As Integer
Dim intRemainder As Integer
Dim intRow As Integer
Dim arraySize As Integer
Dim strSexDigit As String
Dim strArray() As String
Dim i As Integer
'Set exclApp = GetObject(, "Excel.Application") 'When no Excel Workbook is open an error 429 will be returned.
'Debug.Print exclApp
Set wordDoc = Word.ActiveDocument
Debug.Print wordDoc
'Set mySheet = exclApp.ActiveWorkbook.ActiveSheet
'Debug.Print mySheet.Name
'Set mySheet = exclApp.ActiveWorkbook.Sheets("sample")
'Debug.Print mySheet.Name
strPESELfromWord = Trim(Selection.Text)
Debug.Print strPESELfromWord
Word.Application.Visible = True
strSexDigit = Mid(strPESELfromWord, 10, 1) 'Extract 10th digit from PESEL number
Debug.Print strSexDigit
intRemainder = strSexDigit Mod 2
Debug.Print intRemainder
connection.Open "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm"; & _
Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;"";" 'something is wrong in the syntax
'strQuery = "SELECT * From [Simple$]" '[Simple$] is the table name; in this case it's the sheet name;
strQuery = "SELECT * From [data$]" '[data$] is the table name; in this case it's the sheet name;
recSet.Open strQuery, connection
Debug.Print " RecordCount = " & recSet.RecordCount
arraySize = recSet.RecordCount
ReDim strArray(1 To arraySize)
For i = 1 To arraySize
strArray(i) = recSet(i)
Next i
intRow = 2
And why is it a private sub?? Can I make it just sub?? It wasn't me who wrote this. I downloaded this code from here.
I got the connection string from here.
I've read this as well, but they discuss different code structure and I cannot transfer the answer into my own example.
Set Conn = New ADODB.Connection
With Conn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & strWorkbook & "; Extended Properties=""Excel 12.0 Macro; HDR=YES"""
.Open
End With
You are correct that there is something wrong in the syntax here:
connection.Open "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm"; & _
Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;"";"
because the string is not correctly formed. At the very least, you need to change it to this:
connection.Open "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm;" & _
"Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;"";"
(To break that down, if you want your connection string to look like this:
Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm;Extended Properties="Excel 12.0 Macro;HDR=YES;IMEX=1;";
then in VBA you need it to look like this
Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;"";
Then, if you split it into two parts like this
Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm;
Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;"";
you can imagine that your assignment should look like this:
connection.Open "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm;" & "Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;"";"
In VBA, when you want to split a statement into 2 lines, you put a space followed by "_" at the end of the first line, which means that you end up with this:
connection.Open "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = X:\Roesler\Excel\FW 1\customer's_dummy_data.xlsm;" & _
"Extended Properties=""Excel 12.0 Macro;HDR=YES;IMEX=1;"";"
(I am not sure in this case that you need those extended properties anyway).
Going beyond that, your
strQuery = "SELECT * From [data$]"
is correct for a worksheet called "data"
and
recSet.Open strQuery, connection
is fine.
But you can't assume that that query will actually return the number of records in your worksheet. What you see in recSet.RecordCount depends partly on what kind of "cursor" you specify when you open the RecordSet. e.g. When I tested here, recSet.RecordCount was -1. In order to see any data I had to think about testing recSet.EOF and using recSet.MoveNext to move to the first record in the dataset.
FWIW I hope someone else here has a reliable pattern for Excel access via ADO that you can just plug into your code. I don't. But the other thing you will almost certainly need to deal with when using ADO is that when you try to retrieve field values, you always have to consider the possibility that they may be "null", and that trying to use a null value may throw an error.
Re. The "private sub" thing, not it doesn't have to be a Private Sub.
To finally find a Answer to what is causing my system to Crash.. when it was problem of putting in Quotes around a string in a string. This was not displayed clearly anywhere else.
I been working on this for hours and all I got was the Msgbox
Msgbox
Just in Case the image does not get through this is what Error states.
"Error
Microsoft Access Database Engine --> Could Not Find installable ISAM."
This is very annoying and puzzling illogical message for a simple syntax error.
of missing " "" ;"";" Mostly the ;"";" at the end.
Even on Excel 2013 the following Reads and I am
Quoting From the same site mentioned above This is where you can see there is no ";" on the end stringhttps://www.connectionstrings.com/excel-2013/
Xlsm files
Connect to Excel 2007 (and later) files with the Xlsm file extension. That is the Office Open XML format with macros enabled.
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsm;Extended Properties="Excel 12.0 Macro;HDR=YES";
"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.

How to connect to odcb database with excel vbs

thx to google I figured out a lot of weird tricks you can do to connect to simple SQL server or SAP database and such. However, no matter how hard I try I can not create odbc object.
I can pull odbc database to excel, but this is not what I want to do.
I want to use INSERT and DELETE SQL queries.
The simplest line of codes I found were these:
Private Sub ConnectDB()
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & "SERVER=******.****.**;" & "DATABASE=testServer;" & "USER=Mikk;" & "PASSWORD=**;" & "Option=3"
End Sub
I have ticked the box for ActiveX data object 2.8 Library
I get run-time error '-2147467259 (80004005)
Automation error
Unspecified error
Money solves problems :)
I didn't use the correct database name and did not use DSN.
Also using a specific driver was not a good idea.
Even the server aadress was not needed.
Here is the solution:
Sub test_connection()
Dim oConn As New ADODB.Connection
Dim strUsername As String
Dim strPassword As String
Dim strDatabase As String
strUsername = "Mikk"
strPassword = "****"
strDatabase = "test"
oConn.Open "DSN=testServer;" & _
"Database=" & strDatabase & ";" & _
"Uid=" & strUsername & ";" & _
"Pwd=" & strPassword
oConn.Close
Set oConn = Nothing
End Sub

ADO Connection conflicting with other excels (very weird issue)

I created quite a comprehensive End User application in VBA excel the last two months which automated the whole reporting chain based on a daily dump of data in an excel sheet.
All worked fine until the tool went live. When launching my code on a operation desk, sometime the queries on the data dump returns no results.
This only happens when the tool was not opened as a first excel instance.
So, when another excel tool is open first, my tool:
- Returns no results
- An another instance of my tool is opened in read-only
This happens as well on windows 2007 & 2010 and on Win XP & Windows 7.
It opens the other excel on following line (where the issue is situated:
'adoConn.Open sConnString'
Below my code:
Public Function createConnection() As ADODB.Connection
Dim DbPath As String
Dim sConnString As String
Dim adoConn As New ADODB.Connection
DbPath = ThisWorkbook.FullName
'Define connection String
'http://www.codeguru.com/csharp/.net/net_asp/tutorials/article.php/c19307/Whats-in-an-ADO-Connection-String.htm
sConnString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DbPath & ";HDR=Yes';"
'Open the connection
adoConn.Open sConnString
'Return the connection
Set createConnection = adoConn
End Function
The connection string you're using isn't the standard Excel connection string for ADO. Replace:
sConnString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DbPath & ";HDR=Yes';"
adoConn.Open sConnString
with the following:
With adoConn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & dbPath & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;IMEX=1"";"
.Open
End With
I rarely have issues with querying open workbooks with ADO (apart from occasional phantom read-only copies appearing)

Excel 2010 VBA/ADO connection error with XL source and text output

I am using Excel 2010 with a macro to access another daily spreadsheet to pull data for forming an FTP file of records. The specific problem I am having is a runtime connection error. The error I am getting is '-2147467259(80004005)': Unrecognized database format 'C:\Work\Daily FTP Process\Excel DBs and Files\ftp.xlsx'. All I need it to know where to look. Here is the connection string from the watch:
: ConnectionString : "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Work\Daily FTP >Process\Excel DBs and Files\ftp.xlsx;" : String : Module1.XLFixedFieldFile
Here is the pertinent (or impertinent) code:
Dim conn As Object
Dim cmd As Object
Dim psidRecSet As Object
Dim loopIndex As Long
Dim connString As String
Dim sqlString As String
Set conn = CreateObject("ADODB.Connection")
Set cmd = CreateObject("ADODB.Command")
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=" & XLName & ";"
conn.Open connString <==== Here is the line where it is breaking
SOLVED! The connectionstring that worked is as follows:
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & XLName &
"';Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"
Remou, I had tried that, but had something wrong and got an error. The copy&paste of a working line found in another forum was my salvation. I appreciate the help.
For others using this yto solve their problems, to work with Excel 2010, I went to "Tools/Reference" and enabled Microsoft AcriveX Data Objects 6.1 Library and Microsoft ActiveX Data Objects Recordset 6.0 Library.
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & XLName &
"';Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"
conn.Open connString
You want:
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
& xlFile & ";Extended Properties='Excel 12.0 Xml;HDR=No;IMEX=1';"
Note the quotes for the extended property.
You might like to read http://support.microsoft.com/kb/257819, with particular reference to IMEX.

Performance in reading Excel File using OpenXML

As of now im reading all version of excel files using oledbreader. i referred a dll for reading Excel 2010 files. but i cannot read some excel 2010 files using oledbreader. so i would like to use openxml for reading all excel files. is ter any performance issue in this?
which is better?
I have had very good luck using the following code to retrieve table names(worksheet names) and column names from Excel spreadsheets.
Private Sub GetWorksheetData
Dim xlBaseConnStr1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=XLS;Extended Properties=""Excel 8.0;HDR=Yes"""
Dim xlBaseConnStr2 As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=XLS;Extended Properties=""Excel 12.0 Xml;HDR=YES"""
Dim xlName As String
Dim conStr As String
Dim oDia As New OpenFileDialog
oDia.ShowDialog()
xlName = oDia.FileName
If xlName = "" Then
Exit Sub
End If
Dim extType As String = Path.GetExtension(xlName)
Select Case extType
Case ".xls"
conStr = xlBaseConnStr1.Replace("XLS", xlName)
Case ".xlsx"
conStr = xlBaseConnStr2.Replace("XLS", xlName)
Case Else
MessageBox.Show("Unrecognized file type")
Exit Sub
End Select
Dim dtSheets As New DataTable
Using cn As New OleDbConnection(conStr)
cn.Open()
dtSheets = cn.GetSchema("Columns")
End Using
DataGrid1.ItemsSource = dtSheets.DefaultView
End Sub
The above chunk of code returns the following data from a random Excel spreadsheet that I had laying around.
You will need to import the following namespaces for this to work:
Imports System.Data.OleDb
Imports System.Data
Imports Microsoft.Win32
Imports System.IO
If the spreadsheet that you are trying to access has macros, the above code may fail.

Resources