basically, i am uplaoding a dynamic excel file and i want to select all the sheets containing a data and have it in a dataset. But i dont know how, all I can get is from a static sheet name and only one sheet per select, how can i select all shhet within one excel file and have it in a dataset? thanks.
this is what i got so far
Dim exConS As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
excelfile & ";Extended Properties=Excel 8.0;"
Dim exCon As New OleDbConnection(exConS)
Dim dsExcel As New DataSet()
Dim sExcel As String = "SELECT * FROM [SSI-data3$]"
Dim daExcel As New OleDbDataAdapter(sExcel, exCon)
daExcel.Fill(dsExcel)
I think you can use GetSchema with suitable schema name from the Jet schema set to retrieve the names of tables - in Excel, this includes both named ranges and sheets.
You would have to create a UNION query to get every sheet in the one set of data, which would only be suitable if the columns matched.
I think you should use Microsoft.Office.Interop.Excel to get worksheet names and then with a foreach you can get them
Related
Hi I currently have two worksheets in an excel file with one of them acting as a database of all the products we sell, with the columns Product ID, Product Code, and Description (sample below).
I have another worksheet that acts as a product finder tool, where you would paste multiple Product IDs in the first column and it would return the Product code and Description in the adjacent columns (image below).
I currently use an INDEX search to make this happen, but the database sheet has become too big to manage in the same file, leading to severe slow downs. What would be the easiest solution for this? I was thinking of separating the database sheet as an Excel or AccessDB file but I think I will need a lot of VBA manipulation if I do that. Any help would be much appreciated.
You can access your data in Microsoft Access using ADO and doing a SQL query to gather data.
Could you tell me if it's possible to give a cell range to the WHERE clause?
Yes, there is a trick. SQL commands are plain text, you just need to build it with your parameters. Use the operator IN in the WHERE clause.
I made a fake dataset as example. Here's my Excel Product Finder (a table named Table1):
Notice I want the info only of products 6,3 and 2. Now my fake database:
The code to query those specific products:
Sub TEST()
Dim cnn As Object
Dim RST As Object
Dim DatabasePath As String
Dim i As Long
Dim Allid As String
Dim Arrayid As Variant
Dim SQLQuery As String
DatabasePath = "C:\Temp\temp.accdb" 'path to database
'Create a connection object.
Set cnn = CreateObject("ADODB.Connection")
'Create recordset object
Set RST = CreateObject("ADODB.Recordset")
'Open a connection using the OLE DB connection string.
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabasePath & ";Persist Security Info=False;"
'merge all ID into one single string
Arrayid = Range("Table1[PRODUCT ID]").Value
For i = LBound(Arrayid) To UBound(Arrayid) Step 1
Allid = Allid & Arrayid(i, 1) & ","
Next i
Allid = Left(Allid, Len(Allid) - 1) 'get rid of last comma
Erase Arrayid 'clean array variable
'specify query
SQLQuery = "SELECT PRODUCT_TABLE.[Product Id], PRODUCT_TABLE.[Product Code], PRODUCT_TABLE.Description FROM PRODUCT_TABLE " & _
"WHERE PRODUCT_TABLE.[Product Id] In (" & Allid & ") ORDER BY PRODUCT_TABLE.[Product Id]"
'Open a recordset using the Open method
'and use the connection established by the Connection object.
RST.Open SQLQuery, cnn
'copy all data into cells. This will bring full query without headers
Range("A6").CopyFromRecordset RST
'close and clean variables
RST.Close
cnn.Close
Set RST = Nothing
Set cnn = Nothing
End Sub
After executing code I get this:
NOTICE that the output is not sorted as we had before. We asked the products in order 6,3,2 but the output is 2,3,6!
This is because my SQL query got the operator ORDER BY that sorts by ID field. If there is no ORDER BY clause the output will be sorted as it is in the database stored, not as your Excel.
If you really really really need the output to be exactly in the same order that your Product Finder, you can create an UDF function to query each single id once and return a single row for each product but if you work with a lot of data this can consume a lot of time. So think carefully how to approach this part.
By the way, make sure you use the right connection string. You can find many on Access connection strings
I'm using Excel and Access 365 for the record.
I have information on around 100,000 account numbers, far too many for Excel to handle efficiently. I put them into Access.
In Excel, I have a list of about 10 account numbers. This list changes daily. How do I get the account information from Access into Excel? If I was able to keep everything in Excel I would use INDEX MATCH, what is the equivalent to get information from Access?
I would suggest setting up a linked table to Excel within Access, and running an SQL statement. Much simpler than loops in VBA.
Open Access
Create a linked table to the Excel worksheet, which is nothing more than connection information to the worksheet; it doesn't actually store the records from the worksheet.
This allows the following:
From within Access -- run queries that join data between Access tables and the linked Excel table. You can save such queries, use them as RecordSource for a form or report etc.
From within Excel -- you can open an ADO connection from within Excel and run an SQL statement joining Access tables and the linked Excel worksheet. You can then use the Excel Range.CopyFromRecordset method to paste those results into an Excel worksheet.
It sounds like you need to use the 'In' clause. I have the following data points on Sheet2 in Range A1:A5.
Ryan
Sam
Timmy
Tommy
Teddy
Paste the code below into a Module and set a reference to 'Microsoft Active X Data Objects 2.8 Library' under Tools in the VBE Window.
Sub Import()
Dim connect As ADODB.Connection
Dim rec1 As ADODB.Recordset
Dim wb As Worksheet
Dim Wb2 As Worksheet
Dim Param() As ADODB.Parameter
Dim Command1 As ADODB.Command
Dim lrow As Integer
Dim i As Integer
Dim ConcatSQL As String
Set wb = ActiveWorkbook.Sheets("Sheet1")
Set Wb2 = ActiveWorkbook.Sheets("Sheet2")
lrow = Wb2.Range("A" & Wb2.Rows.Count).End(xlUp).Row
'Concatenate desired range into one cell
For i = 0 To lrow
ConcatSQL = ConcatSQL & "'" & Wb2.Cells(i + 1, 1) & "'" & ","
Next i
ConcatSQL = "(" & Left(ConcatSQL, Len(ConcatSQL) - 1) & ")"
'Open Command Object with One Paramter
Set Command1 = New ADODB.Command
With Command1
.CommandText = " Select ID, Price from TABLE where ID IN " & ConcatSQL
.CommandType = adCmdText
.CommandTimeout = 600
End With
'Connect to Data Source
Set connect = GetNewConnection 'Represents Private Function with Connection String
Command1.ActiveConnection = connect
Set rec1 = New ADODB.Recordset
Set rec1 = Command1.Execute()
'Paste Results
wb.Activate
With wb.QueryTables.Add(Connection:=rec1, Destination:=wb.Range("A1"))
.Name = "data"
.FieldNames = True
.Refresh BackgroundQuery:=False
End With
'Close Connections
rec1.Close
connect.Close
Set rec1 = Nothing
Set connect = Nothing
End Sub
Here is a screen shot to show how the variables are created.
I'm 100% certain that you can run a simple query in Access and export the results of said query to Excel. Or, save that query, and import the records in the object to Excel. When you get into larger data sets like you described, you may want to consider using different tools for the job. Python and R come to mind.
This will probably require VBA to do efficiently.
Loop through the account numbers, and for each account number query the Access database (using ADO) and return only the required data for each account.
I would extract the content of excel document. It's possible with devexpress 13.2? Does anybody have any suggestion?
Thanks a lot in advance
Take a look at the DevExpress Spreadsheet Document Server (non-visual component with complete spreadsheet functionality available via its API). It allows developers to create, modify, save and print Excel documents, even when Microsoft Excel or Microsoft Office is not installed on the system. Supported File Formats - XLS, XLSX, XLSM, CSV and TXT;
Example: How to: Load a Document to a Workbook
I have done an import of an excel-file to update a SQL server table in the last days (with the DevExpress Grid only to show the imported data).
I my example, I:
ask the user for the filename (not necessary if you already know the
file name and path)
load the excel-file in a datatable (no devexpress needed for that)
show the datatable in a DevExpress Grid then
Note: in real live, I use the grid only to view/control the loaded data.
I then update an existing datatable on a SQL server from the loaded data in the datatable (code not included here).
Note: In the example, the sheet name always is "Sheet1" - maybe you want to make the sheet name also variable for your scenario...
Note: You don't need DevExpress, if you only want to import an Excel file into a DataTable (see ImportTable = ReadExcelIntoDataTable(cFileName, "Sheet1") and function ReadExcelIntoDataTable()) in code below.
' Chose the Excel-File over Open FileDialog()
' If you don't know the filename & path allready
Dim cFileName As String = ""
Dim filedialog As OpenFileDialog = New OpenFileDialog()
filedialog.Title = "Chose the File"
filedialog.DefaultExt = ".XLSX"
filedialog.ShowDialog()
cFileName = filedialog.FileName
'
If Not cFileName = "" Then
ImportTable = ReadExcelIntoDataTable(cFileName, "Sheet1")
If ImportTable.Rows.Count > 0 Then
Grid_Datenimport.DataSource = ImportTable
' Do some format (if you like)..
GridView2.Columns("ColumnX").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
GridView2.Columns("ColumnX").DisplayFormat.FormatString = "dd/MM/yyyy HH:mm:ss"
GridView2.Columns("ColumnX").Width = 160
End If
End If
Public Shared Function ReadExcelIntoDataTable(ByVal FileName As String, ByVal SheetName As String) As DataTable
Dim RetVal As New DataTable
Dim strConnString As String
strConnString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & FileName & ";"
Dim strSQL As String
strSQL = "SELECT * FROM [" & SheetName & "$]"
Dim y As New Odbc.OdbcDataAdapter(strSQL, strConnString)
y.Fill(RetVal)
Return RetVal
End Function
I have an Excel worksheet that has a list of about 1000 Item Numbers in column A on Sheet1. Currently, I import Sheet1 into an Access table named ItemNumbers and run the following query:
SELECT MyTable.ItemNumber, MyTable.ItemName, MyTable.ItemPrice
FROM [ItemNumbers] INNER JOIN MyTable ON [ItemNumbers].ItemNumber = MyTable.ItemNumber
ORDER BY MyTable.ItemNumber;
And then I copy/paste the output to Sheet2.
How can I do this in VBA in Excel and put the results in a recordset? I can figure out how to loop through the recordset and put the results in Sheet2. I'm just not sure on the code to run the query.
I have the following so far. It just needs to be modified to use the values in Sheet1 Column A.
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\MyDatabase.accdb"
strSql = "SELECT MyTable.ItemNumber, MyTable.ItemName, MyTable.ItemPrice " & _
"FROM MyTable " & _
"WHERE WHERE (((MyTable.ItemNumber)= ??? IS IN Sheet1!A:A ??? )) " & _
"ORDER BY MyTable.ItemNumber;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
Thanks!!!
If I understand right; what you ask is to join a table from Access with a table in Excel (ADODB).
Check this link from SO, and see if it's helpful:
Selecting 2 tables from 2 different databases (ACCESS)
I haven't tried to combine Access and Excel before, but my guess is that it will work for Excel as well.
An alternate way (and that will certainly work):
Run the query without the WHERE clause and store the result in a
recordset;
Store the data from the Excel sheet that you require in a dictionary,
where the ItemNumber (PK?) is the key;
Run through the recordset, and check with the typical dictionary Exists function
if the ItemNumber from each record is available in the dictionary;
If the record is availabe, store the
recordset values in a separate array (or dictionary) that you can
use for further manipulation, (or perform direct actions if that's what you want to do).
Hello
I'm trying to add new column to the Excel worksheet by command
ALTER TABLE [MyTable] ADD COLUMN Field_dest nvarchar
But on execution of the command got exception "Invalid operation"
I tried table name with and without $ at the end , but got the same result
My questions are
1) Is there some wrong in the command above?
2) Is command ALTER table supported for excel table ?
3) Is the alternative way to add column into excel worksheet - preferable via OLEDB ?
Thanks in advance
Alter table will not work, AFAIK, however, you can Create Table or Select Into, which will allow you to create a new sheet. I cannot get this to run against an open sheet.
Dim cn As Object
Dim scn As String
Dim sSQL As String
strFile = "C:\Docs\test.xls"
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
strFile & ";Extended Properties=""Excel 8.0;HDR=Yes;"""
Set cn = CreateObject("ADODB.Connection")
cn.Open scn
''Note that there is no $ on the sheet to be created
sSQL = "SELECT *,'' As NewField INTO [Sheet17] FROM [Sheet4$]"
''Jet data types
sSQL = "CREATE TABLE [Sheet8] (AText text, ANother text)"
cn.Execute sSQL
If you run against an open file, you will get an error to the effect that Sheetn does not exist.
You can use Create Table instead of Alter Table.
Just use your existing table name, then your columns adds to existing sheet
CREATE TABLE [ExistingSheet$] (ID char(255), oldField1 char(255), newField2 char(255))
it's work!