I am tyring to export data from a Word document that has Forms. I can export the data to an excel file with the extension .xlsx, however, I get an error message (Data Type Mismatch in criteria expression) when trying to export the data to a macros enabled excel file with the extnesion .xslm.
Does anyone know why I would be getting this error message? Why does it export to .xlsx but not to .xlsm?
Here is my code:
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=C:\Users\Desktop\OG Database\OG Database.xlsm;" & _
"Extended Properties=Excel 12.0 Macro;"
.Open
.Execute strSQL
End With
I had a similar issue a couple months ago and was able to replicate the issue by defining a column as 'date' formatting in Excel and then trying to insert text.
Excel will sometimes get locked on to the first data-type that is put into it. Excel then will define the whole column as that type. When trying to manipulate that data via ADO it causes this error.
In order to ensure that Excel doesn't get 'confused', try inserting a phony row of data that is not likely to have fields that get confused, like this.
"INSERT INTO [Sheet1$](Colors, SelectedDate, Balance) VALUES('red', #6/25/1950#, 24.76)"
Of course, don't forget to delete it afterwards.
Related
I'm trying to import the data from CSV file using VBA. Here i'm trying retrieve the data without opening the .csv file
Connection used
con.Open ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & short_path & ";" & _
"Extended Properties=""text; HDR=Yes;ReadOnly=true; FMT=Delimited; IMEX=1;ImportMixedTypes=Text;""")
and for that sql used
str_sql = "Select * from [" & str_filename & "]"
rst.Open str_sql, con, adOpenStatic, adLockOptimistic, adCmdText
OLEDB is trying to read the data. So after pasting data from recordset to excel, comments i.e. Long strings are getting truncated. I believe by default it is scanning first 8 rows to determine the datatype.
This is working perfectly when I have the comments/long strings which are more than 255 characters in first 8 rows.
However, the problem comes when more than 255 characters comment/long string is on 9th or '+ rows. so all later comments are truncated to 255.
I'm wandering around the web to find out the solution but got Nowhere.
Note. If I had the small size CSV file then I can do the open/copy/paste/filter/calculation very easily by using VBA to open file and then do the rest.
However, In my scenario the files size is 100+ MB. So i cant open. tried but failed because it goes into non responding mode and crashes later.
so how to achieve this in VBA and Excel.
I have a VBscript that connects to a excel file and queries the data using Microsoft.ACE.OLEDB.12.0. I'm just displaying the recordcount right now but when I have the document open, the count is wrong. When the excel document is closed, it is correct. I'm getting an error now "The connection for viewing your linked Microsoft Excel worksheet was lost" CODE: 80004005 Source:Microsoft Access Database Engine. I've used VBScript to pull this data many times before but never got this error.
Any ideas on what is causing this?
The connection string is this:
cnnExcel.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & strExcelFilePath & ";" & "Extended Properties=" & Chr(34) & "Excel 12.0 Xml;Readonly=1;HDR=Yes;IMEX=1" & Chr(34) & ";"
Recordset is this:
rsExcel.open "SELECT * FROM [col$] WHERE [name] <>''", cnnExcel, adOpenStatic, adLockReadOnly
I solved this when it happened to me. My SQL was failing because source data had a record ID of 10054748 in a cell which was formatted as a date causing an overflow error which caused another non-erroring column to return a NULL, even though the error was not in one of the columns queried. The field's data was type text in any case, and the errant formatting caused by pasting a copied recordset from Toad and XL TextToColumns automatically parsing it based on a different data set parsed earlier in the day! The solution was changing that column's formatting back to General which eliminated the overflow errors. Summary: probably any errors in source data to be selected using SQL and Microsoft.ACE.OLEDB.12.0 can cause null values to be returned and unexpected failure of a where clause that references those null values, source data should be clean, formatting should be minimized and well understood!
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
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.
I have got a table in access that I loop through using a DAO recordset. For every recordset I take a bunch of data to an excel spreadsheet and run it through a model in excel. This produces a bunch of results in excel which are calculated in named cells.
I want to be able to update the current recordset in access with these results but am having a tough time doing it.
I have the following code
code to create a DAO recordset
code to move to first record
code to parse data to excel
code to run a bunch of stuff in excel including a goal seek to calculate results
next I use the follwoing code without success
With MyXL
strSQL = "UPDATE ProductPricing SET Profit = " & .Names("Profit") & ";"
End With
Code to move to next record and loop until EOF
Could you not try to keep everything in access and replicate the goal seeking using a user defined function? Failing that I would keep the code in excel and get the code to “pull” the values into excel and then “push” them to access as opposed to pushing the data to excel and pulling it back