Conditional Saved Import in Access/VBA - vba

I'm fairly new to this stuff, so hopefully someone our there can help me out.
The setup: I've got an Access 2007 database that imports data, then performs a set of queries and exports the results on a monthly basis.
The monthly data is saved as either Excel spreadsheets or in text files in a "Current" folder. I saved the rather tedious import steps for each file to facilitate the process of adding them as tables in Access.
There are a lot of files to import, so I wrote a simple VBA code to run all of the saved imports at once.
Public Sub DatabaseImp()
DoCmd.RunSavedImportExport "Import-Excel1"
DoCmd.RunSavedImportExport "Import-Excel2"
DoCmd.RunSavedImportExport "Import-Txt1"
DoCmd.RunSavedImportExport "Import-Txt2"
DoCmd.RunSavedImportExport "Etc....."
End Sub
Also, I created a macro to run this code and everything works fine.
BUT,
The Problem: Depending on the month, certain files will be included in the 'Current' folder and others won't be.
For example, suppose that this month there is no 'Excel2' file to import into the database.
Is there anyway to modify the code above so that it only tries to perform the import IF there is something there for it to import?
I understand that I could simply do it manually, ignoring the 'Excel2' import. However I would like to keep the process automated.
I'm looking for some kind of conditional IF statement that I could add on to the end of each line, e.g.:
DoCmd.RunSavedImportExport "Import -Excel1"
(ONLY IF there is an excel1 file in the 'current' folder to import)
Ideas, anyone?
Thanks,

You can use the Dir command. If the result is is an empty string, then it doesn't exist.
So, on a Windows machine, Dir("C:\Windows\explorer.exe") will return explorer.exe, but Dir("C:\Windows\bumblebee.exe") will return "".
So set up an If statement.
If Len(Dir(YourFile)) > 0 then
DoCmd.RunSavedImportExport "Import -Excel1"
End if

Related

Access VBA Convert Linked Table to Local

I am running into a problem and can use some advice. I am linking to an excel spreadsheet and then i am trying to convert that link into a table.
my very basic function is as follows
dim mypath as string
docmd.transferspreadsheet aclink, acspreadsheettypeexcel112xml, "importeddata", mypath, true
runcommand acCmdConvertLinkedTableToLocal
this gives me a runtime error 2046
The command or action 'ComvertLinkedTableToLocal' isn't available now.
So, the reason for doing the link and then the conversion is when done manually, it will get rid of all the conversion errors that a normal import will do and then I have my basic VBA scripts which seem to run far quicker in Access than Excel.
Again, any help is duly duly appreciated
Groundhog.
I believe you need to have a specific linked table selected in order to run the acCmdConvertLinkedTableToLocal command. Try something like this after linking:
DoCmd.SelectObject acTable, "importeddata", True
DoCmd.RunCommand acCmdConvertLinkedTableToLocal
Alternatively, have you tried creating an empty table that matches the spreadsheet structure (i.e. using text fields instead of numeric fields) so that you don't get the import errors when you import instead of link?
Thank you for sharing this code example. I had to make one addition to get this to work correctly for me. I was getting a runtime message that the command was not available before adding a DoEvents after the SelectObject and prior to acCmdConvertLinkedTableToLocal.

VBA Dynamic Save As, Microsoft Project to Excel

I am trying to create a macro that will export a Microsoft Project file into an excel file. Through the use of macro recording I have got a line of code that accomplishes this using the export wizard, but I want the file path and file name to be dynamic so I can use this macro on different projects. I have been searching many other threads and the Microsoft website with no luck. Is this possible?
Here is what I have:
sub formatAndSave ()
FileSaveAs Name:="C:\Users\XXXXXX\SharePoint\Projects\ProjectType\HxH\myProject.xlsx",_
FormatID:="MSProject.ACE", map:="myMap"
end sub
One idea I tried was:
Active.Workbook.SaveAs FileName:=Title
Any help would be very much appreciated!
For the sake of simplicity, let's assume for all answers below your project is located at c:\projects\myProj.mpp
I think you're after the string replace function. Something like:
Dim excelFilePath As String
excelFilePath = Replace(ActiveProject.FullName, ".mpp", ".xlsx")
Debug.Print excelFilePath
'the output would be c:\projects\myProj.xlsx
If you're unfamiliar with string manipulation in VB/VBA, just search the web for "VBA string manipulation". Microsoft has a decent article here: https://msdn.microsoft.com/en-us/library/aa903372(v=vs.71).aspx
A few other things that may be handy for you are these variables:
ActiveProject.FullName 'shows full path & name, so you'd get "c:\projects\myProj.mpp"
ActiveProject.Path 'shows just the path, so you'd get "c:\projects\"
ActiveProject.Name 'shows just the file name, so you'd get "myProj.mpp"
Finally, one caveat I've seen is that the ActiveProject.FullName and ActiveProject.Name variables may or may not provide the file extension depending on your local windows environment settings. I've observed that if Windows Explorer is configured to hide file extensions, then these variables also withhold the extension; if Explorer is configured to show them, then they are provided in the variables. Make sure your code is robust to both cases, or make sure you have control over the environment where you code will run.

DataTable.ImportSheet operation failed.Invalid file

I'm running Excel tests on UFT and sometimes I get the error number 20012 which is "DataTable.ImportSheet operation failed.Invalid file".
This is my way of importing the script:
DataTable.ImportSheet filepath,scriptname,"Action2"
filepath is the path of my workbook which conatins many excel sheets (scripts)
scriptname: the name of the script that I want to run
Action2: contains all the call of all possible keywords that may script can contains.
Any help please, why I'm getting this error.
The problem is that this is working well for some scripts and for others not after 3 or 4 run times.
I think the problem is on Excel itself and not on the code, are there any problems when working with Excel 2016 and UFT 12 ?
UFT syntax for importing a worksheet is:
DataTable.ImportSheet FileName, vtSrcSheet, vtDstSheet
This means you need to pass as parameters the filename (and path) to the excel file, the name (or index) of the source sheet you want to import, and then the destination you want this sheet to be (for example "Global" or "Action1" etc)
Unless scriptname happens to be the exact name of the worksheet you are trying to import you will get this error.
If you want to import the whole file use Datatable.Import instead of Datatable.ImportSheet

Export Access Query WITHOUT Formatting

Relatively simple, but I can't seem to work it out. I want to export a query from access into a .csv (tab or comma delimited). When I do it manually through the wizard it works fine. But when I do it via vba, it comes complete with dash formatting that looks like the borders in the table!
I tried two methods and got the same results
DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen
I used it with or without "ExportSpec", which is a specification I created when exporting manually.
This is the second method:
Dim testSQL As String
Dim qd As DAO.QueryDef
testSQL = "SELECT * FROM Qry_Grade"
Set qd = db.CreateQueryDef("tmpExport", testSQL)
DoCmd.TransferText acExportDelim, , "tmpExport",_
"C:\Users\Databoe\Documents\KidsTV\grade.csv"
db.QueryDefs.Delete "tmpExport"
This is a solution I've found which seems like overkill
And this is what the output looks like:
You can see it's not actually split any of the columns when opening the file in excel and that every second line is just a string of "-"'s
What about DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, myQueryName, myExportFileName, True for direct excel file export.
I tried your approaches, but I only get formated text with your first try DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen which is as expected because it's a text export not csv.
With your second method I always get an excel compatible result. Maybe you have an error trap that hides an error and the first grade.csv is not overwritten. Use a different filename for the second method to prevent that.
Found a second trap. You don't specify full file path in first method, but in second. If C:\Users\Databoe\Documents\KidsTV is not your default document path, you have 2 grade.csv in different folders, but you maybe think that you only have one that gets overwritten.
I just ran into this problem myself, and found a great work around. It doesn't save as a .csv, but you can save as a comma delimited .txt file.
Use the export wizard on the External Data tab to export your query as a .txt file without formatting.
Once the file is exported you get a dialogue box asking if you want to save export steps. Click the box and save the export.
There is an action available in the Macro wizard called "Run Saved Import/Export." Select this action and choose your saved export from the dropdown menu.
Very frustrating that even now I cant seem to make Access export a simple csv file. I do not know why they think I need pretty formatting. Try this: open Excel, Click Get Data, From Database, From MicroSoft Access Database. Select the Access Database you wish to export from. Select the table/query we want saved as an csv. This will set up a link to this table. Once imported, save the Excel file to an csv file.

Access not finding an excel file which was created in vba on a network

I have code that opens & alters an excel table, saves it to a new (network) location, and then imports data from the newly formatted excel. The issue I have is that the code can't find the newly created file, saying it doesn't exist. I've played around with adding a 'pause' function, but I'm wondering if there's a way to refresh the network link in vba? Or is there a better method? Files will vary by size.
If I add a break in the code and let it sit for a few minutes it finds the file fine.
Private Sub btnImport_Click()
[other code]
'save excel file onto network location
xlApp.ActiveWorkbook.SaveAs ("\\network\file.xlsx")
xlApp.Quit
'Import file to temp table.
DoCmd.TransferSpreadsheet acImport,acSpreadsheetTypeExcel9, "tblImport","\\network\file.xlsx", True
End sub
Run-time error '3011': The Microsoft Access database engine could not find the object '\network\file.xlsx'. Make sure the object exists and that you spell its name and the path name correctly.
Free up the Excel resources when finished:
xlApp.Quit
'free any other Excel resources, then..
Set xlApp = Nothing
If it is a network issue and you need a delay then you can use Application.OnTime. For 15 seconds:
Application.OnTime Now + TimeValue("00:00:15"), "my_Procedure"
This will run your procedure (my_Procedure()) after the delay, and this procedure can perform the import.