'DoCmd.TransferSpreadsheet' to export to Excel - excel

I need to EXPORT an access table from ACCESS to EXCEL. There are 618499 rows. I tried simple method: right-click - export - excel. It worked only when I choose export with format (without format created blank excel document), but it is not convenient because I'll have to create 10 documents. I tried to use this code but it became red and did not work:
DoCmd.TransferSpreadsheet(
[acExport],
[acSpreadsheetTypeExcel12Xml],
[tab_1],
["C:\Users\admin\Desktop\import_2014\final.xlsx"],
[True])
What should I change in it?
How should I type it in a module.
Or maybe you can offer another simple solution.

All VBA code must be in a sub or function, that is in a module.
Get rid of all those [], and if you want to put each parameter into a new line, use the line concatenation symbol _
DoCmd.TransferSpreadsheet _
acExport, _
acSpreadsheetTypeExcel12Xml, _
"tab_1", _
"C:\Users\admin\Desktop\import_2014\final.xlsx", _
True
EDIT
Either use Call:
Call DoCmd.TransferSpreadsheet(acExport, acSpreadsheetTypeExcel12Xml, _
"tab_1", "C:\Users\admin\Desktop\import_2014\final.xlsx", True)
or omit the parentheses:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
"tab_1", "C:\Users\admin\Desktop\import_2014\final.xlsx", True

Related

Macro only works for english excel version

I've a quick question for one of my vba codes , the code is basically consolidating 12 tables into one sheet called temp range B8. The problem is that if I run it using Excel 2016 English version it works fine on any computer but if the excel is 2016 spanish version , it will fail with error: " Execution Error 1004"
I've created 12 modules with macros and only one is failing using the spanish version for the following code
Range("B8").Consolidate Sources:=Array( _
"Enero[#All]", "Febrero[#All]", "Marzo[#All]", "Abril[#All]", "Mayo[#All]", "Junio[#All]", "Julio[#All]", "Agosto[#All]", "Septiembre[#All]", "Octubre[#All]", "Noviembre[#All]", "Diciembre[#All]" _
), Function:=xlCount, TopRow:=True, LeftColumn:=False, CreateLinks:=True
Changing the reference type from #All to #Todo was the fix , I-m good now
I'm glad you found a solution to your problem for the Italian version of Excel.
Perhaps, you could make some changes to your code so it could handle both cases (English and Italian). For instance, you could use the following function that returns the MsoLanguageID for Excel (inspired by this answer):
Function ExcelLanguage() As MsoLanguageID
ExcelLanguage = Application.LanguageSettings.LanguageID(msoLanguageIDUI)
End Function
You could then use an if-statement to handle both cases like this:
If ExcelLanguage = msoLanguageIDItalian Then
Range("B8").Consolidate Sources:=Array( _
"Enero[#Todo]", "Febrero[#Todo]", "Marzo[#Todo]", "Abril[#Todo]", "Mayo[#Todo]", "Junio[#Todo]", "Julio[#Todo]", "Agosto[#Todo]", "Septiembre[#Todo]", "Octubre[#Todo]", "Noviembre[#Todo]", "Diciembre[#Todo]" _
), Function:=xlCount, TopRow:=True, LeftColumn:=False, CreateLinks:=True
Else
Range("B8").Consolidate Sources:=Array( _
"Enero[#All]", "Febrero[#All]", "Marzo[#All]", "Abril[#All]", "Mayo[#All]", "Junio[#All]", "Julio[#All]", "Agosto[#All]", "Septiembre[#All]", "Octubre[#All]", "Noviembre[#All]", "Diciembre[#All]" _
), Function:=xlCount, TopRow:=True, LeftColumn:=False, CreateLinks:=True
End If
For all the MsoLanguageID values, see MSDN Documentation.

Access Type conversion failure importing from Excel

I'm trying to import an Excel to Access DB, and some customer numbers cannot be imported due to Type Conversion Failure. It is 12 entries out of 66 thousand. Normally the customer number is a number, but these 12 are strings like ABCDEFT001. I tried setting the field of the table to Long Text or Short text, they are still not imported (only to ImportError table). Do you know what else I can try?
Thank you very much in advance!
P.S. I'm trying to import using DoCmd.TransferSpreadsheet
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Inv level", "Path/to/file.xlsb", True, "Sheetname!"
This strategy links to the excel file, instead of directly importing it, and then selects data out of it and casts any fields that need it to the correct datatype.
Sub ImportFromExcel()
Dim pathToFile As String
Dim targetTableName As String
Dim sql As String
pathToFile = "C:\Path\To\File.xlsx"
targetTableName = "ImportResults"
'//create the link
DoCmd.TransferSpreadsheet acLink, _
acSpreadsheetTypeExcel12, _
targetTableName, _
pathToFile, _
True '//This part only if the excel file has field headers
'//import
sql = "SELECT Field1Name, CStr(CustNumber) AS CustNumber, Field3Name INTO NewImportTable FROM " & targetTableName
CurrentDb.Execute sql
'//remove the link
DoCmd.DeleteObject acTable, targetTableName
End Sub
***Two pitfalls of this code to be aware of:
1) You should delete any table with the name "NewImportTable" before running this code, or you'll get a "Table Already Exists" error.
2) If any errors happen in this Sub before you remove the link, you'll have an issue the next time it runs, as it will create a link called "ImportResults1" since "ImportResults" would still exist. The really scary thing is that no errors would be thrown here. It would create "ImportResults1" and then run your sql on "ImportResults"!!

VBA - Update Linked Table of an Access file from Excel

I am trying to change the linked table address from an Access file "Hey.accdb" using VBA coding from an Excel file.
I've coded the script below in my Excel file and it prompts the error "Object required" when I run it. Can someone please help me with this problem. I've been staring at it for too long. Thanks.
Sub RunMacroinAccesswithPara2()
Set Db = CreateObject("Access.Application")
Db.OpenCurrentDatabase "D:\Database1\Hey.accdb"
Db.Visible = True
Db.AutomationSecurity = msoAutomationSecurityLow
DoCmd.TransferDatabase TransferType:=acLink, _
DatabaseType:="Microsoft Access", _
DatabaseName:="V:\Reporting\Quarterly\2018Q2\JP\Data\04\Database\Valuation_Database.mdb", _
ObjectType:=acTable, _
Source:="Valuation_Database_Adjusted", _
Destination:="Valuation_Database_Adjusted"
End Sub
DoCmd belongs to the Access application object.
So use
Db.DoCmd.TransferDatabase ' etc.
Edit
To update the link, you need the TableDef object, set its .Connect property and run .RefreshLink.
See Linked table ms access 2010 change connection string

Excel User-defined functions can't use ArgumentDescriptions in Excel 2007. I'm trying to bypass it in my Add

I have created a couple of user-defined functions in Excel and created a simple add-in so that I can share them with colleagues.
I use Application.MacroOptions in order to give some useful indications for how to use the functions. Especially, I use ArgumentDescriptions to give descriptions for the arguments.
Application.MacroOptions _
Macro:=FuncName, _
Description:=FuncDesc, _
Category:=Category, _
ArgumentDescriptions:=ArgDesc _
HelpFile:= Helpfile
I have just found out that the ArgumentDescriptions parameter is not supported in Excel 2007 and this is causing an error for this version. Excluding this parameter solves the problem.
I don't want to have to distribute two versions of the add-in. I tried to use this code to include the parameter if the version more recent than Excel 2007, but it still gets tripped up on the unrecognized parameter name if used in Excel 2007:
If Left(Application.Version, 2) > 12 Then
Application.MacroOptions Macro:=FuncName, ArgumentDescriptions:=ArgDesc
End If
Is there a way to solve this problem so I can do this all with just one add-in?
Thanks
An easy way to get around the Named argument not found error in the your function is to move the setting of the macro options into 2 separate functions:
If Left(Application.Version, 2) > 12 Then
setUpNewMacroOptions
Else
setUpOldMacroOptions
End If
And then the 2 functions:
Public Sub setUpOldMacroOptions()
Application.MacroOptions Macro:="myMacro", Description:="desc", Category:="cat", HelpFile:="file"
End Sub
Public Sub setUpNewMacroOptions()
Application.MacroOptions Macro:="myMacro", Description:="desc", Category:="cat", ArgumentDescriptions:="blah", HelpFile:="file"
End Sub
As the setUpNewMacroOptions function is never called in Excel 2007, the VBA compiler doesn't try to validate the function so no error.
This procedure works in Excel 2010 with argument descriptiors and in 2007 without them:
Private Sub AddDesc(Macro As String, Description As String, _
Category As String, ArgumentDescriptions As Variant)
#If VBA7 Then 'in Excel 2010 and over
Application.MacroOptions Macro:=Macro, Description:=Description, _
Category:=Category, ArgumentDescriptions:=ArgumentDescriptions
#Else 'in Excel 2007 and under
Application.MacroOptions Macro:=Macro, Description:=Description, _
Category:=Category
#End If
End Sub
Best regards,
Peter Krassoi

Opening CSV in Excel using VBA causes data to appear in two columns instead of one

I created VBA code in Excel 2007/2010 to import data from a CSV file. Unfortunately, when I open the file programmatically, the data is split into two columns (A and B) for certain rows of data.
When I open the CSV File manually, everything displays fine!
Generally the CSV data looks like this (example header row):
TBWAKT;"TBWAKO";"TBSAIS";"TBSKU9 ";"TBSMOD";"TBLETT";"TBKBNR
";"TBBEZ2 ";"TBFAR2
";"TBSUGC";"TBSOGC";"TBEINK ";"TBKBGR ";"TBKBGF
";"TBVKPE ";"TBVKPR ";"TBEKPE
";"TBAUAN";"TBFAAN";"TBREAN";"TBSTAN";"TBRUAN";"TBKPAG";"TBERDT
";"TBDATV ";"TBDATB "
The data that causes problems includes a comma in the text. Here is an example:
JEAN 5 POCHES EXTENSIBLE+1,60M
Here is the code:
Private Sub OpenCSV(x As Integer, wkbDashboard As String, wkbCsvImport As String, wksDestination As Worksheet)
' Opens CSV and copies data to current workbook
Dim wkbCsvImportName As String
Dim r As Range
Workbooks(wkbDashboard).Activate
' Open and read CSV
Workbooks.Open Filename:=wkbCsvImport, Format:=xlDelimited, Delimiter:=";"
wkbCsvImportName = ActiveWorkbook.Name
Screenshot of the problem. The stuff in red is in column B after opening the file.
Add Local:=True as argument in Workbooks.Open
Hope this might help!
I still suspect it's because the extension is CSV. What happens if you rename the file as a .txt?
In order to import data with a separator that is not a comma, you should set the Format attribute to 6 in order to be able to define your delimiter, as described here.
It should also work if you directly set Format to 4
I think when you do it manually Excel is reading the delimiter as ";" and not just ;.
Try this:
Workbooks.Open Filename:=wkbCsvImport, Format:=xlDelimited, Delimiter:=""";"""
EDIT:
the only way I can get this to work is by changing the file extension from csv to txt and then run this code:
Workbooks.OpenText Filename:=wkbCsvImport, _
DataType:=xlDelimited, semicolon:=True
I know two possible workarounds:
1) Change the extension from .csv to for example .xxx and open it like this:
Workbooks.OpenText fileName:="file.xxx", _
Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=1, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, _
Comma:=False, Space:=False, Other:=False, OtherChar:="", _
TrailingMinusNumbers:=True, Local:=True
If you use .csv or .xls, then the excel overrides the settings by it's default values from the OS.
2) In Windows 10, change your locale setting from English - United States to English - United Kingdom. It's strange that it helps, it doesn't matter what the delimiter setting in advanced date/time is. In Windows 7 I think the delimiter setting worked.
Change the cell format to text.
e.g. Cells(1,1).NumberFormat = "#"

Resources