Here's my problem :
I want to retrieve data from an Excel XML spreadsheet (*.xlsx) within another Excel spreadsheet without opening it. So I gave a chance to OLEDB with the ACE Provider.
The connection worked and I made what I wanted, by looping through my recordset. But now I want some optimization, i.e. putting my recordset into excel in a block instead of looping through it.
Therefore I made something like this :
Sub RetrieveData()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=Path\File.xlsx; _
Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"""
.Open
Set rs = .Execute("Select * From [Sheet1$]")
'Problem here
Range(Cells(1, 1), Cells(rs.RecordCount, rs.Fields.Count - 1)) = rs
.Close
End With
Exit Sub
The thing here, is that I'm currently dealing with technologies which I don't know much about them and can't find any documentation on them (e.g. Microsoft ACE 12.0 Provider for OLEDB).
Regards.
(And don't even hesitate to correct my poor grammar)
I think this is what you need:
Cells(1,1).CopyFromRecordset rs
Quite simple, don't you think. But put it instead of this line:
Range(Cells(1,1)................ = rs
And remember to remove comment: 'Problem here :)
By the way, data you get in your sheet don't include columns heading. But I hope you'll cope with that separately.
Related
Set wb = xl.Workbooks.Open(fileName)
Set ws = wb.Sheets("Sheet1")
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileName & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;"";"
Set rs = db.OpenRecordset("Tracking", dbOpenTable)
ws.Cells.ClearFormats
The bug trigger according to access is
Set rs = db.OpenRecordset("Tracking", dbOpenTable)
as "Type mismatch". I have already build a table name as "Tracking" in my access application, so I was confused why it is not processed.
PS. I am trying to add new records from Excel to Access table through recordset.
Thanks in advance!
It seems that the problem does not have anything to do with Excel. In order to help somehow, there should be a way to make a MVCE, which would actually be enough for everyone to copy, paste it and replicate the error.
Something like this in Access is quite enough:
Sub TestMe()
Dim rs As Recordset
Dim db As Database: Set db = CurrentDb
Set rs = db.OpenRecordset("Tracking", dbOpenTable)
End Sub
If you still have problems with even this code, then it is a good start.
I'm a creating a vba macro for an Excel database. The database is about a number of people and the time spent by them on each of their projects. Whenever there's a new user, a new column adds up.
So, I tried with rs.Fields.Append but it's not working. :( can you help me?
Sub AjoutEnregistrement()
Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim Project As String
Dim MyCheck As Boolean
Set cnn = New ADODB.Connection
Dim i As Variant
MyFile = "D:\Users\X\Documents\Checkin__2018.xlsm"
LoginID = "A01825112"
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Fichier & ";Extended Properties='Excel 12.0;HDR=No'"
Set rs = New ADODB.Recordset
rs.Open "SELECT * from [AUGUST$] ", cnn, adOpenDynamic, adLockOptimistic
rs.Fields.Append "LoginID"
rs.AddNew
rs.Update
rs.Close
cnn.Close
End Sub
Excel isn't a database, and you're not meant to interact with it this way. ADODB recordsets let you read/write recordsets to/from Excel, but they're not meant to be updated by VBA; as far as I know, what you're trying to do here isn't possible. It really sounds like Access would serve your needs far better than Excel would.
If you must use Excel, you should just do what you're trying to do directly. That is, add a column to a spreadsheet.
You can use the following sub to do so, given a worksheet and the header of the new column
Sub addHeader(ws As Worksheet, newColHeader As String)
Dim lastCol As Long
lastCol = ws.Cells(1, ws.columns.Count).End(xlToLeft).column
ws.Cells(1, lastCol + 1).Value = newColHeader
End Sub
In your example, you would call it with
addHeader Workbooks("Checkin__2018.xlsm").Worksheets("AUGUST$"), LoginID
You cannot add a column to an ADODB RecordSet after the RecordSet has been opened. Josh's answer is good - add the column in Excel and re-query.
This is something that has had me going round and round in circles for a while now, essentially all I would like to do is to insert the values of an Excel dynamic range into an Access table.
I have had success in doing this by referencing the range as for example, however to make things a little more self sufficient I would prefer to use a dynamic range.
The code I have is as follows:
Sub ExportDistDatatoSql()
Dim cn As ADODB.Connection
Dim STRQUERY As String
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\uMyDB.accdb;"
.Open
End With
ssql = "INSERT INTO Crude_Prods_DB Select * from [Excel 12.0;HDR=YES;DATABASE=C:\TEST\mysheet.xlsm].[n_range]"
cn.Execute ssql
End Sub
The error I am seeing is attached and I have checked an [n_range] does exist in the workbook.
[error seen when attempting to insert data into access table from excel named range]
Any suggestions would be much appreciated.
I learned this the hard way. A dynamic range is resolved only when Excel runs, thus it doesn't exist when you just read the file.
Only a saved and fixed Named Range can be read by Access.
Hey all, have been working on designing a new database for work. They have been using Excel for their daily reports and all the data is stored in there, so I decided to have the back-end of the database in Access and the front-end in Excel, so any analytical work can be easily performed once all the data has been imported into Excel.
Now I'm fairly new to VBA, slowly getting used to using it, have written some code to transfer one of the calculated tables from Access to Excel:
Option Explicit
Public Const DataLocation As String = "C:\Documents and Settings\Alice\Desktop\Database\TestDatabase21.accdb"
Sub Market_Update()
Call ImportFromAccessTable(DataLocation, "Final_Table", Worksheets(2).Range("A5"))
End Sub
Sub ImportFromAccessTable(DBFullName As String, TableName As String, TargetRange As Range)
Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer
Set TargetRange = TargetRange.Cells(1, 1)
' open the database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBFullName & ";"
Set rs = New ADODB.Recordset
With rs
' open the recordset
' .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable
' all records
.Open "SELECT * FROM Final_Table", cn, , , adCmdText
' filter records
For intColIndex = 0 To rs.Fields.count - 1 ' the field names
TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset data
End With
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Sub Company_Information()
Dim companyName As String
On Error GoTo gotoError
companyName = Application.InputBox(Prompt:="Enter Company Name", _
Title:="Company Name", Type:=2)
Exit Sub 'Don't execute errorhandler at end of routine
gotoError:
MsgBox "An error has occurred"
End Sub
The above code works fine and pulls up the desired calculated table and places it in the right cells in Excel.
I've got two problems that I'm having trouble with; firstly I have some cell-formatting already done for the cells where the data is going to be pasted into in Excel; I want it to apply the formatting to the values as soon as they are pasted in Excel.
Secondly; I have an add-on for Excel which updates some daily Stock Market values; these values need to be transferred into Access at the end of each working day, to keep the database maintained, I tried some code but have been having some problems with it running.
The code for this part can be seen following:
Sub UPDATE()
Dim cnt As ADODB.Connection
Dim stSQL As String, stCon As String, DataLocation As String
Dim stSQL2 As String
'database path - currently same as this workbook
DataLocation = ThisWorkbook.Path & DataLocation
stCon = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & DataLocation & ";"
'SQL code for GL Insert to Access
stSQL = "INSERT INTO Historical_Stock_Data SELECT * FROM [Portfolio] IN '" _
& ThisWorkbook.FullName & "' 'Excel 8.0;'"
'set connection variable
Set cnt = New ADODB.Connection
'open connection to Access db and run the SQL
With cnt
.Open stCon
.CursorLocation = adUseServer
.Execute (stSQL)
End With
'close connection
cnt.Close
'release object from memory
Set cnt = Nothing
End Sub
I get the following error with this.
Run-time Error '-2147467259 (80004005)'
The Microsoft Jet database engine cannot open the file 'Cocuments and Settings\Alice\Desktop\Database'. It is already opened exclusively by another user or you need permission to view its data.
I'm fairly new to databases, VBA and Access so any help would be greatly appreciated.
Also I have been told that the above method of having an Excel front-end and Access back-end is not recommended but alot of the analysis they conduct is done through Excel, and the charts feature in Excel is much better than Access in my experience atleast; and that is also one of the requirements for this project.
Thank you advance!
Solution to your first problem:
Sorry to be the bearer of bad news, but your entire first module is unnecessary. Instead, try:
Go to Data->Import External Data->Import Data, select your Access file, select your table, and presto! done!
Right-click on your new "External Data Range" to see a number of options, some related to formatting. You can even keep the original cell formatting and just update the values. I do this all the time.
To update the Excel data table later, there is a "External Data Range" toolbar that allows you to refresh it as well as a "refresh all" option to refresh every table in the Excel file. (You can also automate this thru code. It'll take some trial and error, but you're definitely up to the task)
Regarding your second problem
I've never used it, but there is also a "New Web Query" option in there as well. I assume it can be manipulated and updated the same way.
And lastly
Your choice of the Excel front-end and the Access back-end sounds good for your needs. It gets the data to your analysts in a medium they are familiar with (Excel) while keeping the calculations out of the way in Access. Technically, you could try putting all your calculations in Excel, but that might the Excel file much bigger and slower to open.
Do the data entry/updating/reviewing in Access. One of Access' strengths is using forms that allow you to update the tables without any code. Then allow the users to easily export the data to Excel such as by clicking on some command buttons.
Modules: Sample Excel Automation - cell by cell which is slow
Modules: Transferring Records to Excel with Automation
nothing wrong in principle with the excel/access pairing. I'm not familiar with ADO (I use DAO), but your error message seems to be indicating that the path to the datasource is not fully formed; or you already have it opened and hence are locking it.
I need to add a row to a spreadsheet using VBScript on a PC that does not have Microsoft Office installed.
I tried [Set objExcel = CreateObject("Excel.Application")]
Since Excel does not exist on the PC I cannot create this object.
Is there a way to modify a spreadsheet without Excel?
To use the code below, create an Excel workbook named "Test.xls" in the same folder as the vbscript file.
In Test.xls, enter the following data in cells A1 thru B4:
First Last
Joe Smith
Mary Jones
Sam Nelson
Paste the vbscript code below into a .vbs file:
Const adOpenStatic = 3
Const adLockOptimistic = 3
filename = "Test.xls"
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filename & _
";Extended Properties=Excel 8.0"
query = "Select * from [Sheet1$A1:B65535]"
Set rs = CreateObject("ADODB.Recordset")
rs.Open query, cn, adOpenStatic, adLockOptimistic
rs.AddNew
rs("First") = "George"
rs("Last") = "Washington"
rs.Update
rs.MoveFirst
Do Until rs.EOF
WScript.Echo rs.Fields("First") & " " & rs.Fields("Last")
rs.MoveNext
Loop
At a command prompt, type:
CSCRIPT Yourfile.vbs
It will add a name to the spreadsheet and then write out all the names.
Joe Smith
Mary Jones
Sam Nelson
George Washington
You can try to use the Microsoft Jet Driver:
See here for a vbscript sample. See here for more links and ways to insert rows.
Not without extreme difficulty. Microsoft have released their file format specifications, Excel here, but these are not to be taken lightly, and I think you will have a difficult time using VBScript.
I know...years later but today I needed to figure out how to access an Excel spreadsheet using vbScript without loading Excel on my server. I searched around the net and found your information helpful, but I still needed more so I kept searching. I finally found the solution that I needed and wanted to share it here just in case anyone else has the same issues that as I did.
I was trying to access (read/write) an Excel spreadsheet using vbScript on a Windows 2008 server and I didn't want to install Excel on my server. My solution was here (it uses PowerShell but it is easy to decypher to VBS):
Using vbScript to read from an Excel spreadsheet without Excel installed
Using vbScript to write to an Excel spreadsheet without Excel installed
I hope that this helps someone that needs the same solution in the future.
L8r...
UCG
This is the final version of the script I used, thank you all for the help.
Dim arrValue
arrValue = Array("Test","20","","I","2.25","3.9761","20","60","12","1","","1","1","1")
AddXLSRow "C:\Test.xls", "A1:N109", arrValue
Sub AddXLSRow(strSource, strRange, arrValues)
'This routine uses the data from an array to fill fields in the specified spreadsheet.
'Input strSource (String) = The Full path and filename of the spreadsheet to be used.
'Input arrValues (Array) = An array of values to be added to the spreadsheet.
Dim strConnection, conn, rs, strSQL, index
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strSource & ";Extended Properties=""Excel 8.0;HDR=Yes;"";"
Set conn = CreateObject("ADODB.Connection")
conn.Open strConnection
Set rs = CreateObject("ADODB.recordset")
strSQL = "SELECT * FROM " & strRange
rs.open strSQL, conn, 3,3
rs.AddNew
index = 0
For Each field In rs.Fields
If field.Type = 202 Then
field.value = arrValues(index)
ElseIffield.Type = 5 And arrValues(index) <> "" Then
field.value = CDbl(arrValues(index))
End If
If NOT index >= UBound(arrValues) Then
index = index + 1
End If
Next
rs.Update
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
Without Excel installed I cannot see how you will be able to change an Excel document.
However, If your are using Excel 2007 spreadsheets (xslx) then you should able to use the OpenXML functionality of the .NET Framework to update the contents without Excel physically being installed.
Take a look here for more information on Office OpenXML.
You might want to see this question. It's C# based, but should give you an insight into the techniques for accessing spreatsheets.
Sorry to be late to the party. The fact that no one's mentioned VSTO probably means that I'm misunderstanding the question. And at any rate I've heard mixed reviews from folks using it.
I believe the simple answer to your question is no because you need the Excel COM object which is only installed when Excel is installed. This used to be one of the real drawbacks of writing an Office app--the need for the entire application (Excel, Word or whatever) in order for an end-user to use it.
Use EPPlus.
epplus.codeplex.com
You can do most things that you can do with VSTO, without excel installed.