Is there a way to copy an Access database from within itself through VBA code? I've tried using fso.CopyFile and FileCopy but they lead to permission errors since the file is already open.
1 Answer
I found that you can use a shell32.dll function to copy the open file. I even added the progress bar functionality. Here is the code
Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
Public Const FO_COPY = &H2
Public Const FOF_SIMPLEPROGRESS = &H100
Public Type SHFILEOPSTRUCT
hWnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAnyOperationsAborted As Long
hNameMappings As Long
lpszProgressTitle As Long
End Type
Public Sub VBCopyFile(ByRef strSource As String, ByRef strTarget As String)
Dim op As SHFILEOPSTRUCT
With op
.wFunc = FO_COPY
.pTo = strTarget
.pFrom = strSource
.fFlags = FOF_SIMPLEPROGRESS
End With
'~~> Perform operation
SHFileOperation op
End Sub
I just needed to call the VBCopyFile Sub with the appropriate parameters and it worked.