VBA to import Excel Spreadsheet into Access line-by-line - excel

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.

Related

Is it possible to append Excel data to an Access database file using VBA within Excel?

I have three cells in an in Excel 2010 worksheet, say a1, a2, and a3. Every time the user runs my Excel macro, I need it to take the info in those cells and append it to an existing Access DB file. That is all that will be in the db file, just a running list.
So, I don't want to IMPORT from Access. I want this all to happen on the Excel side, preferably without opening access at all. Is this possible or can I just tell my husband to forget about it?
If it IS possible, can someone give me a clue as to how to go about it? Or where to learn about it? I'm ok with VBA in Excel but have zero experience with Access or even with databases.
Thanks!
Create a reference to the Microsoft DAO 3.6 object library and start playing with this code:
Sub DBInsert()
Dim DB As DAO.Database
Dim RS As DAO.Recordset
' open database
Set DB = DAO.OpenDatabase("C:\Users\Myself\Desktop\MyDB.mdb")
' open table as a recordset
Set RS = DB.OpenRecordset("Table1")
' add a record to the recordset
RS.AddNew
' fill fields with data ... in this case from cell A1
RS.Fields("Field1") = [A1]
' write back recordset to database
RS.Update
' important! cleanup
RS.Close
' forget to close the DB will leave the LDB lock file on the disk
DB.Close
Set RS = Nothing
Set DB = Nothing
End Sub
Create a button on the sheet and place this code inside the Button_Click() so the user can send the data to your DB when all entry is done.
Further resources:
Office 2013 / Data Access / How do I ...
Choosing ADO or DAO for Working with Access Databases

Microsoft Access Runtime 2013 - import from Excel

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.

Publishing Excel Named Ranges to SharePoint Programmatically

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

Get table data in Excel 2007 from query in Access 2007

I have an automated process that is mostly run in Access. But, in the middle, it puts some data in Excel to scrub it into the correct form (it's much faster than doing it in Access), and at the end it opens another Excel file and puts data from some Access queries into the Excel file. For these connections from Excel to Access, I accomplished them all by going into Excel and doing Data --> Get External Data --> From Access, then selecting the Access file and the query I want to get the data from and tell Excel to make it into a Table.
So, I do that one time and then I want to be able to run this automated process that simply refreshes the data. To do this refreshing of the data, I do a line like:
Worksheets("Data").Range("A1").ListObject.QueryTable.Refresh _
BackgroundQuery:=False
The problem is, half the time (and I can't figure out why it does it one time and not another), it says "Do you want to connect to path\filename?" Of course I do, how else would the table refresh? So, this stops the automation. Even if I click Yes, I still can't get it to continue on. If I click Yes, it opens up the Data Link Properties. After I click OK for that, it opens a window titled "Please Enter Microsoft Office Access Database Engine OLE DB Initialization Information". It has info in it, including the path and name of the data source I want to access, but if I click OK, it says, sorry that didn't work, would you like instead to connect to (and then it lists the exact same path and file name it just said didn't work). It repeats the steps I just mentioned, and after that it errors out.
In case it matters, here is the (basic idea) code I use to connect to Excel from Access:
Public Sub ExportToExcel()
Dim ObjXLApp As Object
Dim ObjXLBook As Object
Dim ExcelFilePath As String
ExcelFilePath = CurrentProject.Path & "\"
Set ObjXLApp = CreateObject("Excel.Application")
Set ObjXLBook = ObjXLApp.Workbooks.Open(ExcelFilePath & "filename.xlsm")
ObjXLApp.Visible = True
' Runs the "DataSetUp" macro in the Excel file.
ObjXLApp.Run ("DataSetUp")
' The DataSetUp macro saves the Excel file
' Quit Excel
ObjXLApp.Quit
' Free the memory
Set ObjXLBook = Nothing
Set ObjXLApp = Nothing
End Sub
I have no idea how to fix this! Any help would be much appreciated.
This may be happening because your access database is still open from which the new excel file needs to input data back into. The database cannot be open when this takes place, hense the reason why excel errors and asks for another location to connect to.
So, I would work on generating the needed scrubbing via vba inside access probably.

Exporting Access Query to Excel

I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.
Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub
Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.
Any suggestions or ideas a very welcome.
The short story, is you can't. You might be able to do some scripting on the Excel side to format the resulting file. If you want something pretty, you probably want to create a report.
You could, instead mount the excel sheet as a table, and then on a separated sheet in the excel file, reference the first sheet, and format the second sheet for viewing.
if you use DoCmd.TransferSpreadsheet and create an original and then edit it so that the formatting is correct, you can then run DoCmd.TransferSpreadsheet again and it will update the file with the values but keep the formatting.
However, if a human then changes the file by adding new tabs, or adding calculations, etc, then the DoCmd.TransferSpreadsheet will no longer work and will fail with an ugly error message. So what we do in our enviroment is DoCmd.TransferSpreadsheet to an original file with formatting, and follow that up in the VBA by copying the file to the users desktop, and then opening that copy so the user doesn't mess up the original source excel file.
This approach is a minimum code, clean, and easy to maintain solution. But it does require a extra "source" or original file to be hanging around. Works in Access 2007.
You also would like the results to end up on a new tab. Unfortunately, I think it will take some excel automation to do that. The VBA inside Acccess can call a function inside the VBA in Excel. That VBA could then copy the tabs as needed.
My idea would be a hybrid of Excel automation from Access and creating a template in Excel as well that would have a data table linked to your query.
To start create your data table in Excel. You can start three rows down and two columns to the right if you want or wherever. Go to your data tab and click access, find your db, choose your query you want to link to, choose table as the radio button but click properties next instead of ok, uncheck the enable background refresh, this part is critical ... under the definition tab in the connection string you will see a part that says Mode=Share Deny Write change that to Mode=Read, this will make sure that the query refreshes without errors from an MS Access VBA while the db is open and will keep your users from writing back to the db in case your query is a writeable query. Once you set that up you can adjust the table formatting however you choose from the table design tab and it will keep that formatting.
For the purposes of this we are going to assume you started the table in cell B4 ,and your named the worksheet CurrentDay, for purpose of the following VBA example be sure to replace that reference with your actual placement.
Next go back to Access and write your VBA first ensure that in your VBA window you have the reference to Microsoft Excel 12.0 Object Library is selected by going to Tools > References and selecting it from the alphabetical listing.
Create your sub as follows:
Sub query1_click()
Dim xl as Excel.Application
Dim wbk as Excel.Workbook
Dim wks as Excel.Worksheet
Dim RC as Integer
Dim CC as Integer
Set xl = New Excel.Application
Set wbk = xl.wbk.Open "X:\Filelocation\FileName.xlsx" 'name and path you saved the file you previously created
xl.Visible = True
'The above is not necessary but you may want to see your process work the first few times and it will be easier than going to task manager to end Excel if something fails.
RC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("B:B")) + 3 'This will count the rows of data in your table including your header so you can copy the data to another tab dynamically as the size of your table expands and shrinks we add 3 to it because we started at row 4 and we need the location of the last row of the record set.
CC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("4:4")) + 1 'This counts the header row and adds one space because we will use this as a location holder for our copy / paste function
Set wks = xl.wbk.Worksheets.Add
wks.Name = format(date(),"MM_dd_yy") 'this will name the tab with today's date... you can eliminate this step if you just want the sheets to be the generic Sheet1, Sheet2, etc.
With xl.wbk
.Worksheets("CurrentDay").Range(Cells(4,2),Cells(RC,CC)).Copy
.wks.PasteSpecial xlPasteValues 'This pastes the values so that the table links do not paste otherwise every tab would just refresh everyday.
.wks.PasteSpecial xlPasteFormats 'This gets your formatting.
.RefreshAll 'This will refresh your table
Wend
With xl
.Save
.Close False
.Quit
Wend
Set xl = Nothing
Set wbk = Nothing
Set wks = Nothing
End Sub
That should get you to have your data to not start on A1 of your sheets, save your old data each time, and automate the steps from access.

Resources