I was wondering if it was possible to move data from an excel sheet and store it in a Microsoft Access datbase. I have a lot of sheets of data with a similar format, and I would like a table for each of them in access. I would also like to retrieve data from the database, but i figure I should learn how to store data first. I found this code, I don't know if someone could explain how it works( Or if it is nothing like what I'm looking for)? I have read power programming in excel with vba, so I know basic vba, but not this database content(Probably more).
Public Sub DoTrans()
Set cn = CreateObject("ADODB.Connection")
dbPath = Application.ActiveWorkbook.Path & "\FDData.mdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
cn.Open scn
ssql = "INSERT INTO fdFolio ([fdName], [fdOne], [fdTwo]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
End Sub
Also if you have any book recommendations that would cover this/links, that would also be appreciated.
I'm sure it can be done in Excel, but I don't know it off the top of my head.
But it's fairly easy to do in Access (also uses VBA). Look at the TransferSpreadsheet method. If you combine it with saved import specs, it can do a lot.
You also have the choice of importing the data into a new table, or you can just link to the spreadsheet and have it act like a table. Linking is useful when you don't want all the spreadsheet info and want to query it.
Here's a link on the command syntax: http://msdn.microsoft.com/en-us/library/office/ff844793(v=office.14).aspx
The code that you have found transfers data to an already existing database named FDData.mdb that is probably already set up to look exactly like your excel worksheet. Can I ask why you don't just use Access? It is easier to use VBA to create excel sheets from Access than it is to do the opposite. There is also the import database from excel worksheet feature in Access, are you trying to automate this process for a vast number of excel worksheets? Otherwise you are better off just using the wizard. We might be able to help more if you can tell us exactly what you are trying to do, linking up Excel and Access via VBA might be more counterproductive than just picking one and dealing with the downsides unless you are prepared to write a whole lot of code.
Since you know about accessing cell value in your excel and know how to access an AccessDB as recordset in VBA, this wont be too hard for you ..
I'm sure Google will give you nice direction for it !
And I found this link for you .. http://www.ozgrid.com/forum/showthread.php?t=76110
Related
I'm trying to call part information from SQL to Excel. When a user enters a part number, Excel queries the SQL database and retrieves details about the part (price, description, etc).
I was able to import the data, and use a vlookup to pull in the values, however the import is quite large.
There were some VB scripts out in the webs that would pull data directly from the SQL database into the cells, but those are out of date for Excel 2013.
I'm using the following statement for SQL to pull all the data on the table:
SELECT
PartNum,
PartDescription,
UnitPrice
FROM erp.Part
Ideally would like a script that only asks for a specific part, using WHERE PartNum = part and returns the requested data in a row.
Thanks in advance for any info/help.
your question is vague at best, and you didnt even provide code youve tried. Here is a basic sql from excel vba script
Sub TrackerInput()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = DBEngine.OpenDatabase("pathtoyourfilewhichmightneedotincludecredentialsGoogelitforyourself")
Dim vAr$
vAr = "your input of choice" '.ie part number you were suggesting
Set rs = db.OpenRecordSet("SELECT PartNum, PartDescription, UnitPrice FROM erp.Part WHERE PartNum=" & vAr & ";")
TheLocationWhereYouWantTheDataReturned.CopyFromRecordset rs
End Sub
Your references will need to be set OBV
Solved by handing in my resignation, apparently im too stupid or don't know how to git good enough to do this job anymore. Going to follow my passion and sell umbrellas on the beach.
I'm writing some code in VBA behind Excel to pull some summary numbers out of potentially huge text files (10M+ rows) out on a network drive. In the past, these numbers have been pulled using greps in linux, but I was hoping to implement something that could be done with a click of a button in Excel for ease of use.
My solution works, but it's like 25 times slower than a linux grep - takes 4 minutes to query 10M records, while the grep can do it in 10 seconds. Should I not be using ADO for this? Why is it so slow, aside from the fact that text files obviously aren't indexed? Is there a better solution that could still be coded without too much hassle in VBA, or is it a lost cause? I'm using Excel 2007 and the ADO 6.0 library. Here is some sample code:
Sub RunSQL()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"";" & _
"Data Source=\\network\share\path\;"
rs.Open "select count(*) from Customers.tab where CHANGE_FLAG = 'Y'", cn
Range("A1").CopyFromRecordset rs
rs.Close
cn.Close
End Sub
I developed an Access database solution that is using Excel automation to open xls and xlsx files so I can import specific cells that I need.
Now I had to deploy my software to an user that does not have Office nor Excel installed and is using Runtime do run my program and I can not use automation any more.
Is there any way I can open an Excel file without Excel and import lets say cell B7 and cell E4 ? I dont need to import it in the table directly but to operate with results from xls in the memory (as I did with Excel object) and save it later.
Thanks in advance.
With some (quite severe) limitations, it is possible to use Jet (i.e., the Access database engine, an ageing version of which is a standard Windows component) to read XLS files at least. For the limitations see here:
http://support.microsoft.com/kb/257819/en-gb
As for an example...
Function ReadCell(XLSFileName As String, SheetName As String, CellName As String)
Dim DB As DAO.Database, RS As DAO.Recordset
Set DB = DBEngine.OpenDatabase(XLSFileName, False, True, "Excel 8.0;HDR=No;")
Set RS = DB.OpenRecordset("SELECT * FROM [" + SheetName + "$" + CellName + ":" + CellName "]")
ReadCell = RS(0)
RS.Close
DB.Close
End Function
Sub Foo
MsgBox ReadCell("C:\Users\ExeBat\Documents\Test.xls", "Summary Details", "C5")
End Sub
My guess is not without a 3rd party library of some sort. Potentially you could read the file as text if it was stored as office open XML, my guess is that MS encrypts/obfuscates your standard xls/xlsx file by default so you cannot though. If Excel isn't available on your user machines in all cases you might need to look into having the source data in another format (text, csv, etc), I know that is probably not an ideal answer though.
I have an excel file with named ranges saved in a document library in SharePoint. I created some excel web access web parts in order to display the excel files I have. My problem is I can't seem to find a way to publish my excel files so that only the named ranges will show up.
I know this can be done manually by setting the browser view options when saving it to SharePoint but I need to do it via code because I need to run it on multiple SharePoint sites.
I was checking Visio services and saw that it had ServerPublishOptions I was wondering if Excel service have something similar that I can use. I was also looking at PublishObjects of excel interop but I'm not sure if it will address my issue.
This code select a range and insert into a sharepoint List using ADO, it is a easy way for me.
Public Const strSharePointInfo = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;DATABASE=http://sharepoint.server.com/Path/;LIST={12312456-124A-78BC-B8E7-1E526B74A015};"
Sub InsertRecordSetOnSharePoint(Rg as Range,ShtName as String)
'Bruno Leite
'http://officevb.com
Dim cn As ADODB.Connection 'Conexao para a Lista do SharePoint
Dim i As Integer,SQL as string
'sql to insert
SQL = "INSERT INTO [LISTNAME] (SELECT * FROM [Excel 12.0;DATABASE=" & ShtName & "].["& rg.name &"$])"
'open connection
cn.Open strSharePointInfo
'run SQL
cn.Execute SQL
Set cn = Nothing
Debug.Print "Insert OK"
End Sub
I'm debugging some code and need to find out where a
DoCmd.TransferSpreadsheet acImport, , ".....
fails so I've decided to import it 'manually' line-by-line to see where it falls over.
I suppose something like this is what I'm looking for:
mySpreadSheet = ConnectTo(Spreadsheet.xlsx)
while(!mySpreadSheet.EOF)
get(mySpreadSheet.nextLine)
SQL("UPDATE MyTable with mySpreadSheet.nextLine")
I've tried Googling to no avail. Any help is much appreciated!
Additional info:
The column names of the spreadsheet and the Access table are identical.
Every data type is nvarchar(MAX) (Or "Memo" as Access calls it)
The table is a linked table to SQL Server 2008
ADO works well if you have a well defined sheet layout of your data (HansUp answer). If you need added control before loading the objects, you can hook into the excel workbook, and then pull out whatever data you like. It really depends on the level of control you need.
Public Sub LoadExcelToAccess(xlPath As String)
'uses late binding to open excel workbook and open it line by line
'make reference to Microsoft Excel xx.x Object Model to use native functions, requires early binding however
Dim xlApp As Object 'Excel.Application
Dim xlWrk As Object 'Excel.Workbook
Dim xlSheet As Object 'Excel.Worksheet
Dim i As Long
Dim sql As String
Set xlApp = VBA.CreateObject("Excel.Application")
'toggle visibility for debugging
xlApp.Visible = False
Set xlWrk = xlApp.Workbooks.Open(xlPath)
Set xlSheet = xlWrk.Sheets("Sheet1") 'modify to your perticular sheet
'depends on what your trying to do with the sheet
For i = 1 To 10
'quick and dirty: best to load items into custom class collection, then do processing there
sql = "Insert Into [Temp] (Col1) VALUES (" & xlSheet.Cells(i, 1).Value & ")"
DoCmd.RunSQL sql
Next i
'make sure to dispose of objects
xlWrk.Close
xlApp.Quit
Set xlSheet = Nothing
Set xlWrk = Nothing
Set xlApp = Nothing
End Sub
You can create an ADO connection to your spreadsheet (see Connection strings for Excel 2007), then open an ADO recordset with that connection (see StackOverflow: ADODB recordset in VBA says excel field is empty when it's not for example).
Then move through the recordset rows, and create a SQL INSERT statement using the row's values.
strInsert = "INSERT INTO MyTable (first_field, second_field) VALUES ('" & -
rs2.Field(0).Value & "', '" & rs2.Field(1).Value & "');"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailonerror
That code snipped assumes first_field and second_field are text data types. If they are numeric, lose the single quotes.
I think that does roughly what you asked. However, before resorting to code I would check whether the spreadsheet imports cleanly into a new native Access table. (Also, check whether the data types and constraints on that new table are compatible with those of the linked SQL Server table.) If that works, maybe try importing the spreadsheet directly into SQL Server from the Management Studio, or whatever tool is appropriate.
For troubleshooting purposes, try linking to the spreadsheet and see what problems you encounter, including data displaying wrong when you view it in datasheet view.
You can also try just copying your Excel data to the clipboard and pasting it into your Access table. Whatever fails will get written into a 'Paste Errors' table by Access.
Two additional options:
Link the spreadsheet in Access like a table. In Access 2007, go to "external data" pane and select "Import Excel Spreadsheet". You should import to an existing datatable, a new datatable or just link to Excel file. Then, you would work with this new "Excel" table like an Access table (regarded the performance issues, in last case).
Try to fix the Docmd.TransferSpreadsheet problem. I've been using this method for some years, and it works fine, despite it ought to be a little tricky in some cases (I belive its your case). Please, its worthy if you give more information about your problem with this method, including your Access and Excel version.
I hope I've helped. Good luck.