MSAccess - TransferDatabase - File locked open? - ms-access

I am attempting the following in an AccessDb via VBA:
Export a single table from current DB into a new DB in the same directory, via a Query/TransferDatabase. This seems to work as expected.
Dim ws As Workspace
Dim db_new as Database
strPath = CurrentProject.Path & "\Backend_Database\"
strDBFilename = strPath & Raw_Count_File.accdb"
Set ws = DBEngine.Workspaces(0)
Set db_new = ws.CreateDatabase(strDBFilename, dbLangGeneral)
DoCmd.TransferDatabase acExport, "Microsoft Access", _
strDBFilename, acTable, "tmp_RawCountFile", "Raw_TblMatchedTB"
Within the same function used above (to create the new file), I am attempting next to ZIP the new file into the same directory. The result is 1K Byte ZIP file (it's an empty ZIP ).
If I breakout the code segment that creates the ZIP file into separate function (i.e., under another button), the function works as expected and the proper ZIP file is created.
My Question:
I am guessing the new DB file and subsequent TransferDatabase is leaving the new_db file hanging open and inaccessible to the ZIP function. I attempted to set the various objects = nothing prior to the ZIP function, but same result. Only if I exit the first function and call a second function will it work as desired.
Can I add something to the end of the TransferDatabase function to ensure the resulting file will be available for the ZIP task?
My preference is not to add a secondary button press to this task...
Any suggestions to get me going?
Thanks!

Try to Set db_new = Nothing before zipping, in order to close the newly created db.

Related

Data extracted from Acces to Excel is automatically getting over to extra sheet than the defined sheet

I am trying to get some data extracted from MS Access to Excel sheet which is a kind of already defined template. For example , i use an excel file with say one sheet named Result (with some pre-defined data) as a source file and then i copy the same to an output file. Then some OutputTable from MS Access is extracted in output file using DoCmd.TransferSpreadsheet with explicitly mentioned to get extracted in Result sheet . The data is coming fine but the sheet Result is not used though an extra sheet named Result1 gets created with same data as OutputTable of Ms Access.
Code i am using is mentioned below:
SourceFile = CurrentProject.Path & "\Template\" & "Input_Template.xlsx"
DestinFile = CurrentProject.Path & "\Output\" & "Output_" & sDateTimeStamp & ".xlsx"
FileCopy SourceFile, DestinFile
DoCmd.TransferSpreadsheet acExport, , "OutputTable", DestinFile, False, "Result"
I have these folders Template (having Input_Template.xlsx file) and Output folder created on my system under same path where the Database is placed.
Could anyone tell if i'm doing it in wrong way or is there any configuration required or i might be missing something. Any help would be highly appreciated.
Thank You!!!
Honey
TransferSpreadsheet is not suitable for exporting to pre-formatted template. Use CopyFromRecordset method from Excel library instead. Example below will dump content of OutputTable to "Result" spreadsheet of destination template file starting "B2" cell.
Dim xlApp As Object
Dim xlWork As Object
Dim xlSheet As Object
Dim rsExportResults As Recordset
Set rsExportResults = CurrentDb.OpenRecordset("OutputTable")
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWork = xlApp.Workbooks.Open(DestinFile)
Set xlSheet = xlWork.Sheets("Result")
xlSheet.Range("B2").CopyFromRecordset rsExportResults

Drag and Drop File into Microsoft Access

I have a form in Microsoft Access which lets users upload attachments to each record. I'd like to make it a little user friendly by letting users drag and drop files into the attachment field. What is the best way of doing this/how do I do this?
Drag and drop might be a bit more sophisticated, how about VBA code to manipulate what you wish to achieve? This article has a great reference to what you wish to do. http://www.access-freak.com/tutorials.html#Tutorial07
Here is a way to drag and drop "attached" files for use with MS Access database.
(Currently using Office 365 Version 1811)
MS Access currently allows drag and drop to a hyperlink field.
Using this capability this example allows drag and drop to store an attachment file to a storage location while keeping a link to the original and new locations. The event runs when a file is dropped into the HyperlinkIn box on the form or when the hyperlink is changed the normal way.
It is better to store the file in a storage location with a link than to store it within the .accdb file due to the 2GB limitation. You might call this a database + file server architecture. By using the record number and optionally the database and table name and attachment number you can ensure unique file names.
Make a Table and Form with 3 fields.
ID (AutoNumber)
HyperlInkIN (hyperlink)
HyperLinkOUT (hyperlink)
Insert this VBS code for AfterUpdate event for the HyperlinkIn form control.
Private Sub HyperlinkIN_AfterUpdate()
Dim InPath As String
Dim FileName As String
Dim OutFolder As String
Dim OutPath As String
Dim RecordNo As String
Dim FileExt As String
OutFolder = "\\networkdrive\vol1\attachments\" 'specify the output folder
InPath = Me!HyperlinkIN.Hyperlink.Address
RecordNo = Me!ID
If Len(InPath) > 0 Then
FileName = Right(InPath, Len(InPath) - InStrRev(InPath, "\")) 'get the file name
FileExt = Right(FileName, Len(FileName) - InStrRev(FileName, ".") + 1) ' get the file extension with dot
'build the new path with output folder path and record number and date and extension
OutPath = OutFolder & "Record " & RecordNo & " Attachment " & Format(Now(), "ddmmmyy") & FileExt
FileCopy InPath, OutPath
Me!HyperlinkOUT = "#" & OutPath & "#"
MsgBox "Copied file to archives " & vbCrLf & InPath & vbCrLf & OutPath
End If
End Sub
I am somewhat inexperienced with vba so there may be some better ways to ensure and verify a successful file copy but this example works for me and is easy for me to understand. I used the MsgBox to help debug with the actual file copy commented out.
Because this page comes as first when searching for "MS Access drag drop", I'm adding my part here. If you are after some cool UI, you can checkout my Github for sample database using .NET wrapper dll. Which allows you to simply call a function and to open filedialog with file-drag-and-drop function. Result is returned as a JSONArray string.
code can be simple as
Dim FilePaths As String
FilePaths = gDll.DLL.ShowDialogForFile("No multiple files allowed", False)
'Will return a JSONArray string.
'Multiple files can be opend by setting AllowMulti:=true
here what it looks like;

VBS file only works when double-clicked

I am trying to use the Windows 8 Location API in order to get GPS coordinates from a built-in sensor, and return these coordinates to MS Access. However, due to the unsupported variant types used in the API, Access is unable to reliably use its objects. I am trying to come up with a workaround using a VBScript file, and somehow returning the values to MS Access (using 2010 and 2013). The easiest way I could think of was to spit out a txt file to be read by Access and then deleted.
My VBS File works perfectly when I run it from Windows Explorer (double-clicking the file) but I can't find a way to make it work properly when running it from VBA code. Here is the VBS File:
Dim latlongfactory
Dim rptLong, rptLat
Dim report
Dim keepSleeping
Dim fs, f
Dim ts
Set latlongfactory = Wscript.CreateObject("LocationDisp.LatLongReportFactory", "llf_")
Set fs = Wscript.CreateObject("Scripting.FileSystemObject")
f = fs.BuildPath(CurrentDirectory, "gpsTempFile.txt")
keepSleeping = True
latlongfactory.ListenForReports(1000)
Sub llf_NewLatLongReport(report)
rptLong = report.Longitude
rptLat = report.Latitude
keepSleeping = False
End Sub
Do While keepSleeping
Wscript.Sleep(20)
Loop
Set ts = fs.CreateTextFile(f, True)
ts.WriteLine rptLat & "," & rptLong
ts.Close
Set fs = Nothing
Set latlongfactory = Nothing
set report = Nothing
When run through VBA, it doesn't create the text file anymore, and I'm not entirely sure why. I tried adding a Msgbox at the end of the script just to see if the code was running. The Msgbox does come up.
The line I use to execute in Access VBA is:
Shell "Wscript """ & CurrentProject.Path & "\gpscoordinates.vbs""", 1
It runs the VBS file, but the text file isn't getting created and I cannot figure out why. Any help would be much appreciated!
If you want the output file to be created in the same folder in which the script resides, you can use the ScriptFullName property of the WScript object:
outputFolder = fs.GetParentFolderName(WScript.ScriptFullName)
f = fs.BuildPath(outputFolder, "gpsTempFile.txt")

Code to Kill current Excel file, then Export to new Excel file without opening output file

I have a database that is linked to a few others. The db in question has some script that exports a table to an Excel ".xlsx" with a name that is linked to other databases. Basically data entry is done in one db and then the other db pulls in the information live so we have real time updating.
However, after the kill sequence completes and the new file is exported, the Excel file opens up. This causes a problem with the second db not being able to see real time updates since the new export file does not actually overwrite the previous since the previous has opened automatically. I need help telling the Excel export files not to open.
I know I should Dim the file name but I haven't :-).
Below is the code, any help is much appreciated.
Private Sub Form_Activate()
'Delete Existing File First; then create new
On Error Resume Next
Kill "\\ct13nt003\MFG\SMT_Schedule_Files\SMT Line Progress Files\SMT2Updated.xlsx"
On Error GoTo 0
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "SMT2Export", "\\ct13nt003\MFG\SMT_Schedule_Files\SMT Line Progress Files\SMT2Updated.xlsx", True
Going out on a limb here since I don't really do VBA in Access but I do a lot with Excel so try something like:
Private Sub Form_Activate()
Const xlFileName as String = "\\ct13nt003\MFG\SMT_Schedule_Files\SMT Line Progress Files\SMT2Updated.xlsx"
Const shortFileName as String = "SMT2Updated.xlsx"
Dim xlApp As Object 'Excel.Application
Dim xlWb as Object 'Excel.Workbook
'Delete Existing File First; then create new
On Error Resume Next
Kill xlFileName
On Error GoTo 0
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "SMT2Export", xlFileName, True
'Get the Excel Application
Set xlApp = GetObject(,"Excel.Application")
'Get the specific workbook
Set xlWb = xlApp.Workbooks(shortFileName)
'Close the workbook
xlWb.Close
'Quit Excel (if needed)
'xlApp.Quit
'Clean up
Set xlWb = Nothing
Set xlApp = Nothing
End Sub
Subscript Out of Range Error
Use the file's name instead of the full path with the xlApp.Workbooks method, per revision above.
There is another potential reason for this error, but this is the most likely.
Reading through your scenario, I'm stumped since I've never had that kind of problem with "Killing" a file. Maybe like another users suggested, you should turn off "On Error Resume Next", at least until you figure out why this error is happening.
Another suggestion would be to try a different deletion method, like
myFSO.DeleteFile "\\ct13nt003\MFG\SMT_Schedule_Files\SMT Line Progress Files\SMT2Updated.xlsx"
That code has On Error Resume Next just before Kill xlFileName. That means if the Kill fails for any reason, it will fail silently.
I have no idea whether that issue contributes to your problem, but suggest you try it this way instead.
'Delete Existing File First; then create new
'On Error Resume Next
If Len(Dir(xlFileName)) > 0 Then
Kill xlFileName
Else
' xlFileName does not exist; no Kill required
End If
'On Error GoTo 0

MS Access Auto Link Excel Spreadsheets

I have a directory structure where I am managing the requirements of a system with each component of that system having its own directory. the requirements of each component are stored in a excel workbook that has multiple worksheets(# of worksheets are static). I am currently using access as a central location to view the information in these sheets and perform queries on them. I hate having to manually link new excel files every time a new component documentation is added to the directory. Is there a way that when everytime I start access it will search the directory tree of stored excel files and automatically link them to access if they're not linked and update my save queries to include the new files. I was thinking that I could save the sub directory names in a table and all the filenames in those sub directory in another table that references the other table, so as it searches the filesystem it compares names to the table. Is this possible if so could someone point me in the right direction.
You can use Dir or the FileSystemObject recursively to get files from a directory tree. Access stores the link information of files in the connect property of the TableDef or you can get it from:
SELECT msysobjects.Database
FROM msysobjects
WHERE (((msysobjects.Database) Is Not Null));
You can get worksheets like so:
''Requires reference to the Microsoft Excel x.x Object Library
Dim strFileName As String
Dim objXL As New Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Object
''objXL.Visible = True
strFileName = "C:\Docs\LTD.xls"
Set wkb = objXL.Workbooks.Open(strFileName)
For Each wks In wkb.Worksheets
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel9, _
wks.Name, strFileName, True, wks.Name & "$"
Next
''Tidy up
wkb.Close
Set wkb = Nothing
objXL.Quit
Set objXL = Nothing
Or using an ADOX.Catalogue: http://forum.lessthandot.com/viewtopic.php?f=95&t=3712