"Kill" / "FileCopy" leads to permission denied - vba

I'm having a problem with my Access VBA macro which for some reason is breaking on those lines with error "Permission Denied [Run-time error 70]:
sOutputFile = CurrentProject.Path & "\Output Files\Recon\" & sDate & " " & sClient & " Cash Recon.xlsx"
sTemplateFile = CurrentProject.Path & "\Temp Files\Template_Listed.xlsx"
If Dir(sOutputFile) <> "" Then Kill sOutputFile
FileCopy sTemplateFile, sOutputFile
What's getting "pointed out" directly is the "Kill sOutputFile" phrase.
It is worth to mention, that I do not have any of the files open, I have full access to the directories, and not long ago (before declaring sOutputFile and sTemplateFile) they've been both cleared.
Any help is much appreciated and I'm willing to share more of my code if needed.
Edit: Also, from time to time, the macro goes to the next line and breaks at the FileCopy instead.

The logic is not quite right in my opinion, please try the following (FileCopy should be inside an If...End If):
sOutputFile = CurrentProject.Path & "\Output Files\Recon\" & sDate & " " &
sClient & " Cash Recon.xlsx"
sTemplateFile = CurrentProject.Path & "\Temp Files\Template_Listed.xlsx"
If FileExists(sOutputFile) Then
Kill sOutputFile
FileCopy sTemplateFile, sOutputFile
End If
And this is the FileExists function:
Public Function FileExists_1(sFileName As String) As Boolean
Dim obj_fso As Object
Set obj_fso = CreateObject("Scripting.FileSystemObject")
FileExists_1 = obj_fso.fileExists(sFileName)
Set obj_fso = Nothing
End Function

What was the issue in my case, was that I previously used the macro, but the full ran failed. After trying to run it again after few adjustments (not related to the code I posted here), the above issue was happening. All just because I had the file still open somewhere in my excel's memory, hence the file couldn't be deleted.
Thanks for all the contributions guys. You're amazing as always!

Related

VBA FileCopy inside a loop fails after one successful copy; Problem: How to Close files before next use?

..................................................................................................................................................................
Late-breaking news...
P.P.S. I just read that FileSystem.FileCopy is better than just FileCopy. That's what I'm going to try. But I really would like to know how to use FileCopy inside a loop, meaning, "How do I close files used in FileCopy?" For the big picture made clear, read on.
..................................................................................................................................................................
(Using Windows 10 Pro, Word 365 Pro)
The online Help for FileCopy Src, Dest says that it ... Copies a file from Src to Dest [but] does not work on a currently open file. Both ... files must be closed [by] the Close statement.
But the online help for Close, from link supplied on that page connects to help for Close for the Open statement, which says that it "Closes the file(s) previously opened with the" Open statement, not the FileCopy statement.
So it is that I'm stumped on what to do with this code, which will copy the first code module in the Document to a backup location, but not the second.
Pic#1: Info about what's supposedly going to be copied
Pic#2: Original error message without On Error
(I have no clue why all these blank lines. They're NOT in my Body.)
Please ignore all the OnError stuff for now.
When the second code module should have been copied, execution halted with error "File not found".
Sub BackupModules()
Dim prj As VBProject
Dim comp As VBComponent
Dim code As CodeModule
Set prj = ThisDocument.VBProject
Dim k As Integer, n As Integer
Dim Destination As String, Prefix As String
Prefix = "junk"
k = 0: n = 0
On Error GoTo x
For Each comp In prj.VBComponents
On Error GoTo x
k = k + 1
If comp.Type = vbext_ct_StdModule Then
n = n + 1
Destination = Prefix & n
MsgBox "Copying Standard module " & n & " of " & k & " components encountered: <" & comp.Name & "> to " _
& Destination & "; # lines: " & comp.CodeModule.CountOfLines
On Error GoTo x
FileCopy comp.Name, Destination
MsgBox "Success"
Close
Else
x: If Err.Number <> 0 Then: _
msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & Err.Description: _
MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext: On Error GoTo 0: Close:
End If
Next
End Sub
Then I began experimenting (a LOT as you can see) with On Error Goto x being placed at various places (one at a time and then all, as shown) and the nasty-looking but syntactically and logically correct line that starts x: If Err... placed inside the Else block.
Pic#3: Error msg after using On Error
(FWIW, I just spotted Normal in the Err.Source part of the error message above. Online help says, "When an unexpected error occurs in your code, the Source property is automatically filled in. For errors in a standard module, Source contains the project name. For errors in a class module, Source contains a name with the project.class form." Indeed, the code is in a Module within the Normal Project.)
Pic#4: Line causing error that On Error did NOT trap
So what's wrong? I've tried everything I can think of. The only help I could find for Close did NOT mention its use with FileCopy. My Close usages caused no error but did Close close both the source and the destination file? Surely not. First use of FileCopy worked, files (probably) not closed, thus second use of FileCopy failed. Docs say using FileCopy on an open file will cause error.
On Error Goto x or to 0 is neither here nor there. That's why I said to ignore them at first.
The question is apparently "How do I close both files mentioned in FileCopy?"
P.S. Per opening blurb, I'm NOT gonna do this.
I suppose I could use Open ... For Input As File#1 and specify the Module's name, if it's readily available to code, and also Open ... For Output As File#2 for the destination, use a For loop to copy the number of lines, if available, and then Close both. But I hope I get a solution to my problem before I try that since SURELY FileCopy should work within a loop (and doesn't because of improper close).
Thanks to #TimWilliams, who tipped me off to Export, my final "Backup all modules" routine is quite simple.
Sub BackupModules()
Dim comp As VBComponent
Dim prj As VBProject: Set prj = ThisDocument.VBProject
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim destPrefix As String: destPrefix = "C:\Users\Dov\Google Drive\Word\Modules\"
Dim destFilePath As String
For Each comp In prj.VBComponents
If comp.Type = vbext_ct_StdModule Then
destFilePath = destPrefix & comp.Name & " " & Year(Now) & " " & Month(Now) & " " & Day(Now)
Debug.Print "Copying Standard module <" & comp.Name & "> to <" & destFilePath & ">"
comp.Export (destFilePath)
Else
Debug.Print "Skipping component # " & k & ", <" & comp.Name & ">, type " & comp.Type
End If
Next
End Sub

VBScript CopyFile reports Error 53 File Not Found, but has successfully copied file

I'm trying to diagnose an issue with VBScript FileSystemObject.CopyFile, it's reporting Error 53: File Not Found, but it has successfully copied the file! I've tried variations of the CopyFile command, with full destination name or just folder etc no difference, it always copies the file.
Worse, if I purposefully break it, by changing the source file name, I still get Error 53, which is the exact situation I'm trying to catch and report.
On Error Resume Next
'copy the officeUI xml to the Microsoft Office folder
filePath = profilePath & "\Microsoft\Office\"
if not WshFSO.FolderExists(filePath) then
WshFSO.CreateFolder filePath
end if
WshFSO.CopyFile scriptPath & "\Access.officeUI", filePath, True
'copy the foo client zip to \foo
filePath = profilePath & "\foo\"
if not WshFSO.FolderExists(filePath) then
WshFSO.CreateFolder filePath
end if
WshFSO.CopyFile localZip, filePath, True
if Err.Number <> 0 then
'catch that the copy failed
msg = "Failed to copy Foo, please report this to Help Desk." _
& vbCrLf & vbCrLf & "Citrix Server: " & WshNetwork.ComputerName _
& vbCrLf & "Error: " & err.Number & " - " & err.Description
WshShell.Popup msg, , "Foo Launcher", 16
Err.Clear
WScript.Quit
end if
The error is occuring on the final CopyFile call.
The problem was due to the Error handling logic in VBS, it was reporting the error number from an earlier line! The On Error Resume Next allowed the code to continue to run, but subsequent calls, even successful ones, did not overwrite the Err object. So when I did want to check the result, it picked up this previous error.
So from this I think that unless you want If Err.Number... everywhere is that before each 'block' of code you want to error check, clear the Err object first with Err.Clear.
I wish VBScript had On Error Goto like its cousin!

Word VBA MkDir Invalid Path in Sharepoint

I am trying to use VBA to create a folder within Sharepoint at my work. The document is opened from Sharepoint so there should be no credential issues (I would think).
I have tried all of the following and always get Run-time error '76': Path not found
How .Path reads the document's location (having removed the document obviously)
MkDir "https://company.sharepoint.com/directory/directory with spaces"
Without certificate
MkDir "//company.sharepoint.com/directory/directory with spaces"
With backslashes between directories
MkDir "https://company.sharepoint.com\directory\directory with spaces"
With corrected spaces
MkDir "https://company.sharepoint.com/directory/directory%20with%20spaces"
and most combinations of the above.
I noted that it takes much longer for Word to decide it's an invalid path without certificate.
I cannot post the actual paths due to NDA issues, but the above recreation should have all pertinent possible issues within the path. I am not parsing the path from variables or input (though I will later) and they are held within a private sub.
I appreciate any help you can give.
Okay, this took me far longer to complete than I expected. I essentially just grabbed the solution from the link in my first comment link I above and added error handling so that (hopefully) all scenarios have a good exit point and explanation.
Sub SharepointAddFolder()
Dim filePath As String
filePath = "https://web.site.com/SharedDocuments/Folder"
'filePath = Replace(filePath, "https:", "") 'I didn't need these but who knows
'filePath = Replace(filePath, "/", "\")
'filePath = Replace(filePath, " ", "%20")
Dim newFolderName As String
newFolderName = "New Folder"
Dim driveLetter As String
driveLetter = "Z:"
Dim ntwk As Object
Set ntwk = CreateObject("WScript.Network")
On Error GoTo ErrHandler
ntwk.MapNetworkDrive driveLetter, filePath, False ', "username", "password"
If Len(Dir(driveLetter & "/" & newFolderName, vbDirectory)) = 0 Then
MkDir driveLetter & "/" & newFolderName
Else
MsgBox "Folder " & newFolderName & " already exists."
End If
ExitThis:
ntwk.RemoveNetworkDrive driveLetter
Exit Sub
ErrHandler:
Select Case Err.Number
Case -2147024829
MsgBox "Sharepoint site not found"
Case 76
'sharepoint directory not found
MsgBox "Mapping failed"
Case -2147024811
'drive already mapped
Resume Next
Case -2147022646
'drive not found and thus cannot be closed
Case -2147022495
MsgBox "This network connection has files open or requests pending." & vbNewLine & vbNewLine & _
"Either close the files or wait until the files are closed, then try to cancel the connection."
Case Else
MsgBox "Error " & Err.Number & ": " & vbNewLine & Err.Description
End Select
End Sub
Note for those of you desiring to continue to work on temporarily mapping SharePoint drives: this code work without any need for username or password (My company uses Authenticator), but only once you have logged in to SharePoint using Internet Explorer. I learned that, when using IE, an option under “All Documents” called “View in File Explorer” exists. It does not exist for Chrome or other browsers (as far as I know). My intent was to permanently map the drives, but once I had logged in from IE the code worked. You do not even have to stay logged in to IE and, when you return to the SharePoint via IE, you are still logged in (I have done this over a one day no-use period). I assume this something to do with the IE being a Microsoft product and therefore being trusted to keep login credentials.

DLookup not refreshing - VBA to open file path

I'm pulling my hair out on this one.
I put together some code for opening a file associated with records in our database. Newer data has full file paths stored as text in a separate table. Old data does not have a full file path but has enough details to assemble a working path in most cases.
My code checks to see if the older data fields are null and if they are proceed to the newer filepath.
The problem I'm having is with DLookup in the IF statement being stuck on the first file it was used on. No matter what I do, DLookup always returns the same result as the first time I ran the code. I'm stumped.
Private Sub btnOpenFile_Click()
Dim FacID As String
Dim FacIDShort As String
Dim CDID As String
Dim FileName As String
Dim FileURL As String
FacID = [FAC_ID]
FacIDShort = Left(FacID, 4)
On Error GoTo ErrHandler
If IsNull([CD_NUM]) Then ' Checks to see if old file path exists before trying new file path
FileURL = DLookup("[File_Path]", "tblFileDirectory", "[Drawing_ID]")
Application.FollowHyperlink (FileURL)
Else
CDID = [CD_NUM]
FileName = [FILENAME]
FileURL = ("\\SYSTEMXXX\" & FacIDShort & "\" & FacID & "\FILES\" & CDID & "\" & FileName)
Application.FollowHyperlink (FileURL)
End If
Exit Sub
ErrHandler:
LogError (FileURL)
MsgBox ("Error: " & FileURL & vbNewLine & "The URL Does Not Exist.")
End Sub
DLookup("[File_Path]", "tblFileDirectory", "[Drawing_ID]" should actually be more like DLookup("[File_Path]", "tblFileDirectory", "MyDrawingIdColumnInTable = MyDrawingIdToLookFor"

MS Access: how to compact current database in VBA

Pretty simple question, I know.
If you want to compact/repair an external mdb file (not the one you are working in just now):
Application.compactRepair sourecFile, destinationFile
If you want to compact the database you are working with:
Application.SetOption "Auto compact", True
In this last case, your app will be compacted when closing the file.
My opinion: writting a few lines of code in an extra MDB "compacter" file that you can call when you want to compact/repair an mdb file is very usefull: in most situations the file that needs to be compacted cannot be opened normally anymore, so you need to call the method from outside the file.
Otherwise, the autocompact shall by default be set to true in each main module of an Access app.
In case of a disaster, create a new mdb file and import all objects from the buggy file. You will usually find a faulty object (form, module, etc) that you will not be able to import.
If you have the database with a front end and a back end. You can use the following code on the main form of your front end main navigation form:
Dim sDataFile As String, sDataFileTemp As String, sDataFileBackup As String
Dim s1 As Long, s2 As Long
sDataFile = "C:\MyDataFile.mdb"
sDataFileTemp = "C:\MyDataFileTemp.mdb"
sDataFileBackup = "C:\MyDataFile Backup " & Format(Now, "YYYY-MM-DD HHMMSS") & ".mdb"
DoCmd.Hourglass True
'get file size before compact
Open sDataFile For Binary As #1
s1 = LOF(1)
Close #1
'backup data file
FileCopy sDataFile, sDataFileBackup
'only proceed if data file exists
If Dir(sDataFileBackup, vbNormal) <> "" Then
'compact data file to temp file
On Error Resume Next
Kill sDataFileTemp
On Error GoTo 0
DBEngine.CompactDatabase sDataFile, sDataFileTemp
If Dir(sDataFileTemp, vbNormal) <> "" Then
'delete old data file data file
Kill sDataFile
'copy temp file to data file
FileCopy sDataFileTemp, sDataFile
'get file size after compact
Open sDataFile For Binary As #1
s2 = LOF(1)
Close #1
DoCmd.Hourglass False
MsgBox "Compact complete. " & vbCrLf & vbCrLf _
& "Size before: " & Round(s1 / 1024 / 1024, 2) & "MB" & vbCrLf _
& "Size after: " & Round(s2 / 1024 / 1024, 2) & "MB", vbInformation
Else
DoCmd.Hourglass False
MsgBox "ERROR: Unable to compact data file."
End If
Else
DoCmd.Hourglass False
MsgBox "ERROR: Unable to backup data file."
End If
DoCmd.Hourglass False
Try adding this module, pretty simple, just launches Access, opens the database, sets the "Compact on Close" option to "True", then quits.
Syntax to auto-compact:
acCompactRepair "C:\Folder\Database.accdb", True
To return to default*:
acCompactRepair "C:\Folder\Database.accdb", False
*not necessary, but if your back end database is >1GB this can be rather annoying when you go into it directly and it takes 2 minutes to quit!
EDIT: added option to recurse through all folders, I run this nightly to keep databases down to a minimum.
'accCompactRepair
'v2.02 2013-11-28 17:25
'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
' Tom Parish
' TJP#tomparish.me.uk
' http://baldywrittencod.blogspot.com/2013/10/vba-modules-access-compact-repair.html
' DGF Help Contact: see BPMHelpContact module
'=========================================================================
'includes code from
'http://www.ammara.com/access_image_faq/recursive_folder_search.html
'tweaked slightly for improved error handling
' v2.02 bugfix preventing Compact when bAutoCompact set to False
' bugfix with "OLE waiting for another application" msgbox
' added "MB" to start & end sizes of message box at end
' v2.01 added size reduction to message box
' v2.00 added recurse
' v1.00 original version
Option Explicit
Function accSweepForDatabases(ByVal strFolder As String, Optional ByVal bIncludeSubfolders As Boolean = True _
, Optional bAutoCompact As Boolean = False) As String
'v2.02 2013-11-28 17:25
'sweeps path for .accdb and .mdb files, compacts and repairs all that it finds
'NB: leaves AutoCompact on Close as False unless specified, then leaves as True
'syntax:
' accSweepForDatabases "path", [False], [True]
'code for ActiveX CommandButton on sheet module named "admin" with two named ranges "vPath" and "vRecurse":
' accSweepForDatabases admin.Range("vPath"), admin.Range("vRecurse") [, admin.Range("vLeaveAutoCompact")]
Application.DisplayAlerts = False
Dim colFiles As New Collection, vFile As Variant, i As Integer, j As Integer, sFails As String, t As Single
Dim SizeBefore As Long, SizeAfter As Long
t = Timer
RecursiveDir colFiles, strFolder, "*.accdb", True 'comment this out if you only have Access 2003 installed
RecursiveDir colFiles, strFolder, "*.mdb", True
For Each vFile In colFiles
'Debug.Print vFile
SizeBefore = SizeBefore + (FileLen(vFile) / 1048576)
On Error GoTo CompactFailed
If InStr(vFile, "Geographical Configuration.accdb") > 0 Then MsgBox "yes"
acCompactRepair vFile, bAutoCompact
i = i + 1 'counts successes
GoTo NextCompact
CompactFailed:
On Error GoTo 0
j = j + 1 'counts failures
sFails = sFails & vFile & vbLf 'records failure
NextCompact:
On Error GoTo 0
SizeAfter = SizeAfter + (FileLen(vFile) / 1048576)
Next vFile
Application.DisplayAlerts = True
'display message box, mark end of process
accSweepForDatabases = i & " databases compacted successfully, taking " & CInt(Timer - t) & " seconds, and reducing storage overheads by " & Int(SizeBefore - SizeAfter) & "MB" & vbLf & vbLf & "Size Before: " & Int(SizeBefore) & "MB" & vbLf & "Size After: " & Int(SizeAfter) & "MB"
If j > 0 Then accSweepForDatabases = accSweepForDatabases & vbLf & j & " failures:" & vbLf & vbLf & sFails
MsgBox accSweepForDatabases, vbInformation, "accSweepForDatabases"
End Function
Function acCompactRepair(ByVal pthfn As String, Optional doEnable As Boolean = True) As Boolean
'v2.02 2013-11-28 16:22
'if doEnable = True will compact and repair pthfn
'if doEnable = False will then disable auto compact on pthfn
On Error GoTo CompactFailed
Dim A As Object
Set A = CreateObject("Access.Application")
With A
.OpenCurrentDatabase pthfn
.SetOption "Auto compact", True
.CloseCurrentDatabase
If doEnable = False Then
.OpenCurrentDatabase pthfn
.SetOption "Auto compact", doEnable
End If
.Quit
End With
Set A = Nothing
acCompactRepair = True
Exit Function
CompactFailed:
End Function
'source: http://www.ammara.com/access_image_faq/recursive_folder_search.html
'tweaked slightly for error handling
Private Function RecursiveDir(colFiles As Collection, _
strFolder As String, _
strFileSpec As String, _
bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
'Add files in strFolder matching strFileSpec to colFiles
strFolder = TrailingSlash(strFolder)
On Error Resume Next
strTemp = ""
strTemp = Dir(strFolder & strFileSpec)
On Error GoTo 0
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
'Fill colFolders with list of subdirectories of strFolder
On Error Resume Next
strTemp = ""
strTemp = Dir(strFolder, vbDirectory)
On Error GoTo 0
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Private Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
For Access 2013, you could just do
Sendkeys "%fic"
This is the same as typing ALT, F, I, C on your keyboard.
It's probably a different sequence of letters for different versions, but the "%" symbol means "ALT", so keep that in the code. you may just need to change the letters, depending on what letters appear when you press ALT
Letters that appear when pressing ALT in Access 2013
In response to the excellent post by jdawgx:
Please be aware of a flaw in the code for CompactDB() above.
If the database's "AppTitle" property is defined (as happens when an "Application title" is defined in the database properties), this invalidates the "default window title" logic shown, which can cause the script to fail, or "behave unpredictably". So, adding code to check for an AppTitle property - or using API calls to read the Window title text from the Application.hWndAccessApp window could both be much more reliable.
Additionally, in Access 2019, we have observed that:
SendKeys "multi-key-string-here"
... may also not work reliably, needing to be replaced with:
SendKey (single-character)
'put a DoEvents or Sleep 150 here
SendKey (single-character)
'put a DoEvents or Sleep 150 here
SendKey (single-character)
'put a DoEvents or Sleep 150 here
SendKey (single-character)
...to get proper responses from the Access UI.
ALSO for Access 2019:
Sendkeys "%yc" ( <-- works for Access 2016)
is no longer correct.
it is now:
Sendkeys "%y1c"
...and if that little change wasn't enough - try to determine (in code) how to tell the difference between Access 2016 and 2019 - Good Luck!! because
Application.Version alone won't help, and even combining Application.Version and Application.Build is not a guarantee (unless you are in a controlled-release enterprise environment, and then it may work as the possible version/build #s in circulation should be more limited).
Yes it is simple to do.
Sub CompactRepair()
Dim control As Office.CommandBarControl
Set control = CommandBars.FindControl( Id:=2071 )
control.accDoDefaultAction
End Sub
Basically it just finds the "Compact and repair" menuitem and clicks it, programatically.
I did this many years back on 2003 or possibly 97, yikes!
If I recall you need to use one of the subcommands above tied to a timer. You cannot operate on the db with any connections or forms open.
So you do something about closing all forms, and kick off the timer as the last running method. (which will in turn call the compact operation once everything closes)
If you haven't figured this out I could dig through my archives and pull it up.
When the user exits the FE attempt to rename the backend MDB preferably with todays date in the name in yyyy-mm-dd format. Ensure you close all bound forms, including hidden forms, and reports before doing this. If you get an error message, oops, its busy so don't bother. If it is successful then compact it back.
See my Backup, do you trust the users or sysadmins? tips page for more info.
DBEngine.CompactDatabase source, dest
Application.SetOption "Auto compact", False '(mentioned above)
Use this with a button caption: "DB Not Compact On Close"
Write code to toggle the caption with "DB Compact On Close"
along with Application.SetOption "Auto compact", True
AutoCompact can be set by means of the button or by code, ex: after importing large temp tables.
The start up form can have code that turns off Auto Compact, so that it doesn't run every time.
This way, you are not trying to fight Access.
If you don't wish to use compact on close (eg, because the front-end mdb is a robot program that runs continually), and you don't want to create a separate mdb just for compacting, consider using a cmd file.
I let my robot.mdb check its own size:
FileLen(CurrentDb.Name))
If its size exceeds 1 GB, it creates a cmd file like this ...
Dim f As Integer
Dim Folder As String
Dim Access As String
'select Access in the correct PF directory (my robot.mdb runs in 32-bit MSAccess, on 32-bit and 64-bit machines)
If Dir("C:\Program Files (x86)\Microsoft Office\Office\MSACCESS.EXE") > "" Then
Access = """C:\Program Files (x86)\Microsoft Office\Office\MSACCESS.EXE"""
Else
Access = """C:\Program Files\Microsoft Office\Office\MSACCESS.EXE"""
End If
Folder = ExtractFileDir(CurrentDb.Name)
f = FreeFile
Open Folder & "comrep.cmd" For Output As f
'wait until robot.mdb closes (ldb file is gone), then compact robot.mdb
Print #f, ":checkldb1"
Print #f, "if exist " & Folder & "robot.ldb goto checkldb1"
Print #f, Access & " " & Folder & "robot.mdb /compact"
'wait until the robot mdb closes, then start it
Print #f, ":checkldb2"
Print #f, "if exist " & Folder & "robot.ldb goto checkldb2"
Print #f, Access & " " & Folder & "robot.mdb"
Close f
... launches the cmd file ...
Shell ExtractFileDir(CurrentDb.Name) & "comrep.cmd"
... and shuts down ...
DoCmd.Quit
Next, the cmd file compacts and restarts robot.mdb.
Try this. It works on the same database in which the code resides. Just call the CompactDB() function shown below. Make sure that after you add the function, you click the Save button in the VBA Editor window prior to running for the first time. I only tested it in Access 2010. Ba-da-bing, ba-da-boom.
Public Function CompactDB()
Dim strWindowTitle As String
On Error GoTo err_Handler
strWindowTitle = Application.Name & " - " & Left(Application.CurrentProject.Name, Len(Application.CurrentProject.Name) - 4)
strTempDir = Environ("Temp")
strScriptPath = strTempDir & "\compact.vbs"
strCmd = "wscript " & """" & strScriptPath & """"
Open strScriptPath For Output As #1
Print #1, "Set WshShell = WScript.CreateObject(""WScript.Shell"")"
Print #1, "WScript.Sleep 1000"
Print #1, "WshShell.AppActivate " & """" & strWindowTitle & """"
Print #1, "WScript.Sleep 500"
Print #1, "WshShell.SendKeys ""%yc"""
Close #1
Shell strCmd, vbHide
Exit Function
err_Handler:
MsgBox "Error " & Err.Number & ": " & Err.Description
Close #1
End Function
Please Note the following - all of you who favor doing a "Compact on Close" solution for MS-Access.
I used to prefer that option too, until one day, when I received the WORST error message possible from the DBEngine during a Compress & Repair operation:
"Table MSysObjects is corrupt - Table Truncated."
Now, you have probably never realized that THAT error is even a possibility.
Well, it is. And if you ever see it, your ENTIRE DATABASE, and EVERYTHING IN IT is now simply GONE. poof!
What is funny about that is that Access will let you actually reopen the "fixed" database, only, the Access window and menu items are all now utterly useless (except to close the DB and exit access again) because ALL the tables (including the other MSYS* tables, forms, queries, reports, code modules, & macros) are simply gone - and with the disk space previously allocated to them released to the tender mercies of the Windows OS - unless you have additional protection than the bog-standard recycle bin, which won't help you either.
So, if you REALLY want to accept the risk of Compact on Close completely clobbering your database - with NO POSSIBILITY of recovering it, then please...do carry on.
If, OTOH, like me you find that risk an unacceptable one, well, don't enable C&R-on-Close - ever again.
Check out this solution VBA Compact Current Database.
Basically it says this should work
Public Sub CompactDB()
CommandBars("Menu Bar").Controls("Tools").Controls ("Database utilities"). _
Controls("Compact and repair database...").accDoDefaultAction
End Sub
There's also Michael Kaplan's SOON ("Shut One, Open New") add-in. You'd have to chain it, but it's one way to do this.
I can't say I've had much reason to ever want to do this programatically, since I'm programming for end users, and they are never using anything but the front end in the Access user interface, and there's no reason to regularly compact a properly-designed front end.