Microsoft Access Runtime 2013 - import from Excel - 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.

Related

How to deal with co-authoring while editing an Excel file in Sharepoint via VBA

I have an excel file stored in Sharepoint (which is also accessible with Microsoft Teams), with the path: https://organization.sharepoint.com/PathOfFile/myFile.xlsx
The file can be edited by multiple at the same time with the co-authoring feature in Sharepoint.
I want to use another excel file stored locally in my computer to access and modify the one in Sharepoint. This local file has a button with this VBA code in it:
Sub UpdateSP():
f_name = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
Workbooks.Open f_name
Workbooks("myFile.xlsx").Activate
ActiveWorkbook.Sheets("sheet1").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.Value = 9999
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = 0000
ActiveWorkbook.Close SaveChanges:=True
End Sub
In principle it works, the file in Sharepoint is modified. But things go wrong if there's someone editing the file while I run the code, then two versions of the file seem to be created, one for the online-live editing, and the one for my code.
If this happens, the online version of the file won't show the changes made by the code, and whenever the file is opened with the excel app, a pop-up will show asking which version of the file should be kept, losing all the changes done in the disposed version.
I have tried to use the CanCheckOut and CheckOut methods, but CanCheckOut always returns False for whatever reason (there are some questions here with the same issue but I havent been able to find a solution).
Can someone suggest a solution to this issue? Thanks.
I'm not 100% sure it will work on SharePoint, but in theory, ADODB is a library for VBA that has the syntax of objects to use Microsoft's Jet Engine so you can open files AdLockOptimistic---ally. ((look up lock types in ADO.net))
This works on a file directory basis, so if the DB being modified is open, it will handle the update.
Instead of using Excel's Application to open the file, you would establish an ADO connection, and then specify the type of Lock in order to access the Excel's sheets and tables inside it.
This works for shared / network drives, so I'm guessing since SharePoint can be mapped as a file explorer drive, then ADO should work and is worth a try.
Here's a basic example to get you started: ADO question
Try enabling the autosave after activating the workbook.
To do so, add this line:
ActiveWorkbook.AutoSaveOn = True
after the Workbooks("myFile.xlsx").Activate line.
I have had similar issues with collaborative files and making sure the autosave is enabled has solved it.
To be able to incorporate changes that way your code must run inside a coauthoring context.
Instead of opening the document from another doc or local copy, the code must be running inside the same document being opened from the same source URL (Sharepoint or OneDrive), that way the add-in or macro can make changes that Excel itself will handle on a coauthoring context.
I recommend taking a look at Coauthoring in Excel add-ins of the Office Dev Center, including the linked articles inside (specifically "coauthoring", redirecting to the support center, and "About coauthoring in Excel (VBA)" at the bottom with more samples).
CanCheckOut will always return false if a workbook is open. Thus you must check before you touch it. The CheckOut command will not open the file so we must also have an open statement after CheckOut.
Using your example it would look like this;
Option Explicit
Public Sub UpdateSP()
Dim fName As String
fName = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
If Workbooks.CanCheckOut(fName) Then
Workbooks.CheckOut fName
Dim myFile As Workbook
Set myFile = Workbooks.Open(fName)
Dim mySheet As Worksheet
Set mySheet = myFile.Sheets("Sheet1")
Dim startRange As Range
Set startRange = mySheet.Range("A" & mySheet.Rows.Count).End(xlUp).Offset(1)
startRange.Value = 9999
startRange.Offset(0, 1).Value = 0
myFile.Close SaveChanges:=True
Else
MsgBox fName & " can't be checked out at this time.", vbInformation
End If
End Sub

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

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.

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

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.

Resources