Access VBA - Delete All .accdb Except For Open Copy In Folder - vba

I'm trying to write an OnOpen() / OnClose() event that will delete *.accdb files from a user's downloads folder. I've got the snippet below that works great, unless a copy is physically open in the drive:
Public Function DeleteLocalDBs()
strUserName = Environ("UserName")
strPath = "C:\documents and settings\" & strUserName & "\Downloads\"
On Error Resume Next
Kill strPath & "*.accdb"
On Error GoTo 0
End Function
If there's a database copy open, nothing happens.
I've looked through here and google, but haven't found any other solutions. If any of you have ideas/suggestions, I'd appreciate it.
Thanks!
Update: I'm not trying to delete the open database. I'm trying to delete other .accdb's that might exist in the folder, which would be previous versions.

Related

Folder handle not released after Dir checks for existence

The following code checks to see if a folder exists and, if not, creates it. The code works, but a handle that points to the folder is left open if it already exists, which prevents the folder from being deleted or renamed until Outlook.exe closes. I do not understand why this is happening or what to do about it, but a handle should not be open after the folder is checked and potentially created.
Sub Test()
Folder = Environ("USERPROFILE") & "\Desktop\NewFolder\"
Result = Dir(Folder, vbDirectory)
If Result = vbNullString Then
MkDir Folder
End If
End Sub
The first time through the code, the folder is successfully created and no file handles are open:
However, the second time through the code, the folder already exists. MkDir does not execute, but a file handle is left open presumably after Dir executes:
I have tried everything I could find to close all open file handles, but nothing has worked. Any help would be greatly appreciated.
Based on the comments from braX, I was able to prove that the Dir call was somehow responsible for the leftover handle. Calling Dir again on a non-existent folder caused the handle to be released, which solved my problem.
A better solution, which was also suggested by braX, is to use a File System Object. Here is a working solution:
Sub Test()
Dim FSO As FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
Folder = Environ("USERPROFILE") & "\Desktop\NewFolder\"
If Not FSO.FolderExists(Folder) Then
MkDir Folder
End If
End Sub
Thanks, braX!

How to delete a excel file in Sharepoint Online using VBA

As per title, I am trying to write code that deletes an excel file from a sharepoint online folder, using only vba.
Since I am very new to VBA, I have no idea where to begin with
Something as the following code should work.
Please note that the Kill function does not move the file to the trash bin. Use with care!
Sub RemoveSharePointFile()
Dim folder As String, file As String, fulladdress As String
folder = "https://example.sharepoint.com/sites/test/"
file = "test.xls" 'must include extension
fulladdress = folder & file
Kill fulladdress
MsgBox "File '" & file & "' was successfully deleted.", vbInformation
End Sub
on cmd create a local folder point to sharepoint with "net use" (net use x:\collaborate.yousite.com#SSL\sites...) then
delete the file from the local driver
kill x:\yourfile.pfd

LOG file for a VBA userform event activity

I am trying to get an MI LOG for the usability of my userform i have created for my team.
I currently reached at a stage where i can only keep a track log of when the workbook has been opened and by who. But i want to go a bit further and also LOG what activities are performed on the user form such as what the user is searching and the results it pulls out.
See code below that i have currently in place: THE BELOW CODE IS PLACED IN MY MODULE:
Sub LogInformation(LogMessage As String)
Const LogFileName As String = "C:\TEXTFILE.LOG"
Dim FileNum As Integer
FileNum = FreeFile ' next file number
Open LogFileName For Append As #FileNum ' creates the file if it doesn't exist
Print #FileNum, LogMessage ' write information at the end of the text file
Close #FileNum ' close the file
End Sub
Public Sub DisplayLastLogInformation()
Const LogFileName As String = "C:\TEXTFILE.LOG"
Dim FileNum As Integer, tLine As String
FileNum = FreeFile ' next file number
Open LogFileName For Input Access Read Shared As #f ' open the file for reading
Do While Not EOF(FileNum)
Line Input #FileNum, tLine ' read a line from the text file
Loop ' until the last line is read
Close #FileNum ' close the file
MsgBox tLine, vbInformation, "Last log information:"
End Sub
Sub DeleteLogFile(FullFileName As String)
On Error Resume Next ' ignore possible errors
Kill FullFileName ' delete the file if it exists and it is possible
On Error GoTo 0 ' break on errors
End Sub
AND THIS CODE BELOW IS PLACE ON "ThisWorkBook"
Private Sub Workbook_Open()
LogInformation ThisWorkbook.Name & " opened by " & _
Application.username & " " & Format(Now, "yyyy-mm-dd hh:mm")
End Sub
THE RESULTS I GET FROM A TXT FILE BELOW:
> Number Checker.xlsm opened by #username : 2017-08-30 09:12
> Number Checker.xlsm opened by #username : 2017-09-02 09:19
> Number Checker.xlsm opened by #username : 2017-09-07 09:21
The userform itself is a simple search tool and pulls back results depending on the search, this is where I need help to track on what the user searched for and what results i.e txtbox1 feedback . Is this possible or I'm running on a dead end? :(
Any help would be much appreciated. Thank you
I just want to say thank you all for your advice & help on pointing me to the right direction, i think i have managed to solve it out now, all i needed to do was to put this code under the click event :
LogInformation ThisWorkbook.Name & " - " & " Closed by - " & _
Environ("username") & " - " & Application.username & " - " & Format(Now, "yyyy-mm-dd hh:mm") & " - " & " Number Searched For - " & _
Me.check_number.Value & " - " & Me.number_status.Value
[problem solved] next task now :p
I've created a simple utility that helps me with that. It is called VBA Telemetry.
It connects VBA and Microsoft Azure Cloud for REAL-TIME logging and tracking of Events & Errors from VBA with 1 line of VBA code.
So you can log and track your VBA projects (Excel workbooks, Access projects) wherever in the world they are. And you see what is going on in your Azure Portal Application Insights resource (this is a new product from Microsoft Azure).
For example, if you want to track an Event you can do this with this function:
TrackEvent "CommandButton1ClickEvent"
There is also one more function TrackMetric where we can send also some custom data. For example, we can send, how long did it take for a loop to complete on a user machine.
TrackMetric "Loop1Duration", 100
Or if you want to track Errors (or exceptions) here is a sample code line:
TrackError Err.Description, Err.Number, "CommandButton1_Click"
You need a free account on Microsoft Azure cloud and a free version of this utility.
Here is a video (45 seconds) where I'm showing how to log (track) Events:
Link to 45 sec video Track Events
You can see the details on how to do this in this article, there is also a youtube video (detailed webinar) in this article:
Link to the article
P.S.
As I've said at the beginning this helps me in my project for logging and error tracking in VBA Projects (Excel, Access), this is why I've made this also available for others. If you don't mind that from time to time a msgbox pops up you can use the free version, if not a one-time payment of few dollars will help me to further develop this little utility.
Hope this helps,
Davor

Closing connection to Excel spreadsheet in classic ASP using ODBC

Kind of a wordy title but I have a classic ASP application I am trying to write where a user uploads an Excel spreadsheet and then I take that spreadsheet and import the data into SQL.
I have everything working great but the one thing I'm running into is that after I open the spreadsheet using ODBC and close all the objects that reference it, if I try to delete the file, I get a permission denied error.
If I try to sweep the temp directory before uploading and I run into a previously uploaded file (say within the last two minutes), I get the permission denied error.
If I wait a minute or two, it seems like whatever lock was put on the file is released and I can delete it.
Here's some code:
sPath = Server.MapPath("/_temp/") & "\"
sFileName = Request.QueryString("filename")
Set objFile = Server.CreateObject("Scripting.FileSystemObject")
If objFile.FileExists(sPath & sFileName) Then
objFile.DeleteFile sPath & sFileName, True
End If
'Upload file occurs here
sConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & sPath & sFileName & ";"
adLockOptimistic = 3
sSQL = "SELECT * "
sSQL = sSQL & "FROM Range"
Set rsSystem = objExcel.Execute(sSQL)
'Do stuff
rsSystem.Close
Set rsSystem = Nothing
objExcel.Close
Set objExcel = Nothing
Set objFile = Nothing
Doesn't seem to matter if I try to delete the file before or after I do the import, if I try deleting the file right after a successful import, I get the permission denied error but if I wait a minute, I'm then able to delete it.
This is an issue as users are going to be supplied templates and they may make a correction and immediately re-upload.
Any ideas as to why the lock is not getting immediately released when I close all associated objects?
Thanks!
Edit:
Changing the connection string to use a different driver seems to have done the trick, now when I close the objects I can delete the file with no issue
sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sPath & sFileName & ";Extended Properties=Excel 8.0;"
I've actually found a number of ways to do this.
As stated in the comments of your OP, one option is to use SSIS and import your Excel spreadsheet using a stored procedure.
You can import directly using a stored procedure
Or use a check to test whether the file is locked

Kill Command Deleting Wrong File(s)i

In Access VBA, I have a procedure I've put together to do this:
Allow the user to select zip file(s)
Extract any files from the zip files to the same directory (In this
specific use-case instance, it is ALWAYS extracting Excel files from
Zip files, never any change, and always using the same password)
Then I want the code to Delete the Zip file after extracting the
.xls file.
Everything works beautifully except the delete file portion. The issue is that when I tell it to delete "FileName.Zip", it is deleting "FileName.Zip" AND "FileName.xls"
Is there any way to make sure that he kill command ONLY deletes what I want it to delete? I've used it before on various occasions, and never had this happen before.
Here is the code I am using:
Dim fd As FileDialog
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Variant
Set db = CurrentDb
Set rs = db.OpenRecordset("tblProjectPath")
Set fd = FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = True
fd.Title = "Select TOC Return File(s) to process"
fd.InitialFileName = rs.Fields("ProjectPath") & "\FilingReports\*.zip"
fd.Show
For Each i In fd.SelectedItems
'Debug.Print i
Debug.Print '------------------------'
Debug.Print i
Unzip (i) 'The bit calling the command line unzip utility to unzip the file - just telling it to extract all files to the current folder.
Debug.Print i
'Kill i
'had to take out the kill bit, b/c it was deleting both the .zip and .xls files which is not desired nor expected
If InStr(i, ".zip") Then
Kill i 'Tried to specify only .zip files even though think I shouldn't need to, but it's still deleting .xls files
End If
Next i
Edit: Add Unzip code to post:
Unzip code:
Sub Unzip(Path As String)
Dim strUnzip As String
Dim QU As String 'quotation mark
QU = Chr(34)
strUnzip = QU & "c:\program files (x86)\winzip\wzunzip" & QU & " -s" & _
"ZipPassword " & _
Path & " " '& _
Call Shell(strUnzip)
End Sub
At this point, I don't really think a "real" answer will come about. However, I'll post what I've decided to do with the particular process I'm writing this code for anyway.
I'm going to use a folder structure to divide up the files:
1. Place zip file(s)
2. Unzip files to a 2nd folder
3. After processing Excel files in 2nd folder, move to a 3rd "complete" folder.
This will get around the deleting wrong files bit.
Also, it appears that the cause for the issue is related to something to do with the call to the WinZip Command Line Unzip utility (wzunzip) in the Unzip code above, or else something with the tool itself. I thought that maybe it was b/c the tool was asking me if I wanted to overwrite existing files, but that wasn't the case, b/c I had the same issue when there were no files to overwrite.
Anyway, I'm attempting to close this one up at this point. Thanks to Wayne G. Dunn for his assistance on this.