Access VBA Macro to run pass through query - ms-access

I have a pass through query built in Teradata set to export data to an Excel spreadsheet. I'm trying to automate it, but when I run the macro or open the query, a window pops up asking for the data source. I have an ODBC connection created and I'm thinking there has to be a way to make the macro pass the data source name so it will run without interaction.
Edit: Adding Macro as requested
Function AutoExec()
On Error GoTo AutoExec_Err
DoCmd.OutputTo acOutputQuery, "Performance Interval Data", "ExcelWorkbook(*.xlsx)", _
"filepath\filename.xlsx", False, "", , acExportQualityPrint
DoCmd.Quit acExit
AutoExec_Exit:
Exit Function
AutoExec_Err:
MsgBox Error$
Resume AutoExec_Exit
End Function

Couple of concerns, (can't validate any of this right now as I do not currently have access to Access for testing), but it looks like:
You're trying to OutputTo a query, to the best of my knowledge that
is not feasible.
Your file path is setup as filepath\filename.xlsx unless that is the actual location and name of your Excel sheet, something seems
wrong there to me.
I don't really think this macro relates to an ODBC of any sort in its current state.
But, you should at least start with fixing the filepath issue. That should be the full path to your Excel file and the full name of the file as well. (i.e. C:\TEMP\TestExcelSheet.xlsx)
All that being said, you may want to just go with something like this (although its a little difficult to tell if this is what you actually want or not):
'Export Excel file from Query
DoCmd.TransferSpreadsheet acExport, , "acOutputQuery", _
"C:\TEMP\TestExcelSheet.xlsx", True
NOTE: "acOutputQuery" should be the actual name of your passthrough query, "C:\TEMP\TestExcelSheet.xlsx" would be your destination path, and True adds the query's headers into the sheet, False to ignore the headers.

Related

MS Access unable to locate my excel range when importing

I have this code that works on one spreadsheet, but not another. I am just trying to automate the transfer of an excel data range to an access table, like so
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "UsysFastTrack", strFilePath, False, strRange
strFilePath and strRange are just strings that contain the full file path (including the worksheet name and extension) and the name of an excel range in the worksheet, respectively. This line causes an error
The Microsoft Access database engine could not find the object ...
This error appears a lot online and somewhere I saw the advice to try the import wizard to see what I get and lo and behold, right as I hit the last Next
This is the exact same error and it stops me dead in my tracks. What's funny is that you can see the range exists in the spreadsheet before your very eyes.
What's going on here?
Looks like the names of your named ranges are not valid, they are similar to regular ranges. Try to change names

VB6: Read CSV File Into Access Table Using DoCmd.TransferText Error

In a VB6 program, with an Access 2000 database, I want to read a .CSV file, with table field names in the first record, into a new Access table.
Here is my VB6 code:
With CreateObject("Access.Application")
.OpenCurrentDatabase "C:\Database1.accdb"
.DoCmd.TransferText , , newTable, importFile, True
.Quit
End With
The DoCmd.TransferText command gives me the following error:
Error # 3107 (MSAccess: Record(s) cannot be added; no insert permission on 'Table Name'.)
Any ideas what I'm doing wrong?
Seeking clarification - are you running this with block from the database you are also opening through .OpenCurrentDatabase? If so, it is my understanding that call is for opening Access from another application (MSDN), so you may be blocking yourself from editing the records. DoCmd.TransferText by itself should suffice to import the records if this scenario's assumption is true.
For future purposes note you can insert code with greater legibility by clicking the Code Sample icon or pressing Ctrl + K when writing your submission.

Output MS Access Query to Excel with vba

Working with MS Access 2007, I have a query I'd like to run and export the results to a specific workbook in a saved Excel workbook. I have the following code written using DoCmd. First I open the query (this works) and then I try to output the results to excel.
DoCmd.OpenQuery "MyQueryName", acViewNormal, acEdit
DoCmd.OutputTo acOutputQuery, "Aging By Desk - Onboarding Team", acFormatXLS, _
"filepath.SuperTest.xls", "SuperTest.xls", True
However, when this code is run, I get the following error message: "An Expression you entered is the wrong data type for one of the arguments". I've been playing around with each argument, but can't seem to locate the problem. Any ideas? Am I on the right path?
You've got too many arguments. From Microsoft's website:
expression.OutputTo(ObjectType, ObjectName, OutputFormat, OutputFile, AutoStart, TemplateFile, Encoding)
Take out one of those Excel filenames you have and it should work.

Running VBA macro within Access 2010 from external VBScript

Not sure this is possible, but it seems like it should be doable.... it is 2013 after all! And some forum posts I found suggest it is, but I have not been successful in getting it to work...
I have an Access 2010 db with a macro that downloads files from 3 different web sites and then proceeds to import the data and process it. It runs for 1hr and 17 mins.
I want to schedule this macro to run at 4am so it is all done and dusted by coffee time and work start 8am... So I created a VBScript to run this, which will then be placed into the Task Scheduler for the desired time.
It is a single user DB, my use only on my PC.
I have done some research but I cannot seem to get this working. Here's what I have so far:
Macro inside "Main" module in Access 2010 inside of "Pricing Model.accdb":
Public Sub Download_And_Import()
ProcStep = ""
ExecStep = 1
DoCmd.SetWarnings False
'Empty the Execution Progress table
DoCmd.RunSQL "DELETE * FROM EXECUTION_PROGRESS"
Call Update_EXECUTION_PROGRESS(Format(Now(), "YYYY/MM/DD HH:MM:SS"), ExecStep, "Starting Download_Files Main Procedure...")
Call Download_Files.Download_Files
Call Update_EXECUTION_PROGRESS(Format(Now(), "YYYY/MM/DD HH:MM:SS"), ExecStep, "Finished Download_Files Main Procedure...")
Call Update_EXECUTION_PROGRESS(Format(Now(), "YYYY/MM/DD HH:MM:SS"), ExecStep, "Starting Import_Files Main Procedure...")
Call Import_Files.Import_Files
Call Update_EXECUTION_PROGRESS(Format(Now(), "YYYY/MM/DD HH:MM:SS"), ExecStep, "Finished Import_Files Main Procedure, closing application now...")
DoCmd.SetWarnings True
End Sub
I then created the following VBScript to run Access VBA Macro externally:
dim accessApp
set accessApp = createObject("Access.Application")
accessApp.OpenCurrentDataBase("G:\Pricing DB\Pricing Model.accdb")
accessApp.Run "Download_And_Import"
accessApp.Quit
set accessApp = nothing
I get the message "Illegal function call, Line 4" which is the step:
accessApp.Run "Download_And_Import"
Any ideas / help is highly appreciated! Thanks in advance!
M
I don't see anything wrong with the VBScript itself. I copied your code, changed the db file name and procedure name, and it ran without error. So my guess is the VBScript error "bubbles up" from Access when it tries to run the procedure.
Open Pricing Model.accdb in Access, go to the Immediate window (Ctrl+g), type in the following line and press Enter
Application.Run "Download_And_Import"
If that throws an error you surely have a problem in that procedure. If it doesn't throw an error, you could still have trouble running it from a scheduled task if the procedure requires Windows permissions and you haven't set the task to run under your user account.
If you need to troubleshoot the procedure, first add Option Explicit to the module's Declarations section. Then run Debug->Compile from the VB Editor's main menu. Fix anything the compiler complains about. Repeat until the code compiles without error.
Disable DoCmd.SetWarnings False during troubleshooting because it suppresses information. Consider whether substituting the DAO Database.Execute method for DoCmd.RunSQL will allow you to avoid turning SetWarnings off at all.
You could try including the ProjectName:
accessApp.Run "[Pricing Model].Download_And_Import"
The project-name defaults to the database name, and square-brackets are needed because of the spaces.
This shouldn't be necessary, because your Sub is Public, but worth a try.
I ran into the same (msg) issue the script was OK! Problem was i was testing the script with the database opened as I was in development mode, as soon i closed the Database the script worked well.Close the database before testing the script.

simple import form in Access

how to create an access form which has import excel file button. and after selecting excel file it automatically creates a table in the database with collumn headers as excel first row and data as excel other rows. if you think i am not putting any effort please give me suggestion or reference and ill do it on my own.
For versions of Access since 2003, you can use the File Dialog to allow the user to browse for the file they want, prior to that, you can use API calls. If this is overkill for you, you can have the user type in the file name and path, but you will have to check that it exists using code (Dir may suit).
It would be best to use TransferSpreadsheet method of the DoCmd object (available in any version of Access from, AFAIK, 1997 onward) to import the spreadsheet. This can be run as VBA (code) or a macro.
If we assume that you are able to create a form and wire up a button you have two issues:
The file open dialog.
Triggering the import.
For 1 you should be able to use the standard Microsoft file dialogs - my VB.OLD and Access are spectacularly rusty (no access 2007) but you can reference the appropriate COM assemblies from Access after which it becomes fairly easy.
2 is a bit more interesting - I beleive you can pretty much do this by menu selection from within access in which case, at least as a first step, you should be able to automate the same steps - pretty much anything you can do from a menu you can also do by calling the relevant command from VBA. The more complex solution would be to create VBA logic to create a linked table that links to the Excel file and then do a create table query and then drop the link.
In terms of effort, the form is something one would expect you to be able to do without much help - however automating something like an import from excel is not necessarily obvious.
An example using Access 2003 would be as follows for selecting a file:
Dim fDialog As Office.FileDialog
Dim strFile As String
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.InitialFileName = "C:\temp\*.xls"
.Filters.Clear
.Filters.Add "Excel file", "*.xls"
.Filters.Add "All Files", "*.*"
If .Show = True Then
strFile = .SelectedItems(1)
End If
End With
Debug.Print strFile
Note you would need to add a Reference to the Office 12 Object Library
To Import the file you can use the TransferSpreadsheet Function of the DoCmd Object. For E.g.
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "ExcelImport", strFile, True
The Access table called ExcelImport would have to already exist in the database.